JAVA中,从命令行中输入一个字符串,要求从中随机选择6个字符
4个回答
展开全部
package com.test;
import java.util.Random;
import java.util.Scanner;
public class RandomTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入字符串:");
Scanner scan = new Scanner(System.in);
String source = scan.next();
int sourceLength = source.length();
int randomLength = 6;
if(sourceLength < 0){
return;
}
Random rand = new Random();
StringBuilder result = new StringBuilder();
for(int i=0;i<randomLength;){
int randomNum = rand.nextInt(randomLength);
if(randomNum >= sourceLength){
continue;
}
i++;
System.out.println(randomNum);
result.append(source.charAt(randomNum));
}
System.out.println("随机的6个字符为:"+result);
}
}
直接复制可以运行
import java.util.Random;
import java.util.Scanner;
public class RandomTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入字符串:");
Scanner scan = new Scanner(System.in);
String source = scan.next();
int sourceLength = source.length();
int randomLength = 6;
if(sourceLength < 0){
return;
}
Random rand = new Random();
StringBuilder result = new StringBuilder();
for(int i=0;i<randomLength;){
int randomNum = rand.nextInt(randomLength);
if(randomNum >= sourceLength){
continue;
}
i++;
System.out.println(randomNum);
result.append(source.charAt(randomNum));
}
System.out.println("随机的6个字符为:"+result);
}
}
直接复制可以运行
追问
为什么经常出现一样的随机数呢?
追答
package com.test;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class RandomTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入字符串:");
Scanner scan = new Scanner(System.in);
String source = scan.next();
int sourceLength = source.length();
int randomLength = 6;
if(sourceLength set =new HashSet();
for(int i=0;i= sourceLength || set.contains(randomNum)){
System.out.println("set存在随机数:"+randomNum);
continue;
}
i++;
set.add(randomNum);
System.out.println(randomNum);
result.append(source.charAt(randomNum));
}
System.out.println("随机的6个字符为:"+result);
}
}
这样就可以了。
展开全部
private static Random randGen = null;
private static char[] numbersAndLetters = null;
public static final String randomString(int length,string TestString) {
if (length < 1) {
return null;
}
if (randGen == null) {
randGen = new Random();
numbersAndLetters = TestString.toCharArray();
}
char [] randBuffer = new char[length];
for (int i=0; i<randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(TestString.length-1)];
}
return new String(randBuffer);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
先看看这串字符长度
然后产生6个 这个长度之内的随机数,不重复的
然后用substring输出
然后产生6个 这个长度之内的随机数,不重复的
然后用substring输出
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
x=random
char=charAt(x)
char=charAt(x)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询