我试图从用户那里收集一些数据并用用户输入显示。我给出的例子是:
Filename: output.txt
number of lines: 4
Line Length: 8
Character Set: ABC123
2CB3A32C
BB13CAA3
C3A21CB2
CC2B13A3
我目前已经获得了用户输入,但我不知道如何根据输入显示随机字母和数字。这是我的代码。任何帮助都会很大。 必须使用循环显示数据。
public static void main(String[] args) throws IOException
{
int lineNum = 0;
int numChars = 0;
String charSet = "";
String userInput = "";
String filename;
//Creates a Scanner Object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get the filename.
System.out.print("Enter a filename: ");
filename = keyboard.nextLine();
System.out.print("Enter number of lines: ");
lineNum = keyboard.nextInt();
if( lineNum < 1 || lineNum > 20){
lineNum = 20;
System.out.println("Defaulting to 20 lines");
}
System.out.print("Enter number of characters in each line: ");
numChars = keyboard.nextInt();
keyboard.nextLine();
if( numChars < 1 || numChars > 20){
numChars = 20;
System.out.println("Defaulting to 20 characters");
}
System.out.print("Enter character set: ");
charSet = keyboard.nextLine();
//Put all the input together to display the results
PrintWriter pw = new PrintWriter(filename);
pw.println("\nFilename: " + filename);
pw.println("Number of lines: " + lineNum );
pw.println("Line Length: " + numChars );
pw.println("Character set: " + charSet );
pw.println("\n" + userInput );
pw.close();
// Read the file
BufferedReader br = new BufferedReader(new FileReader(filename));
for (String line; (line = br.readLine()) != null;) {
System.out.println(line);
}
}
答案 0 :(得分:1)
试试这个。
Random random = new Random();
for (int i = 0; i < lineNum; ++i) {
for (int j = 0; j < numChars; ++j)
pw.print(charSet.charAt(random.nextInt(charSet.length())));
pw.println();
}
答案 1 :(得分:0)
这可能有助于您走上正确的轨道:
import org.apache.commons.lang.RandomStringUtils;
System.out.println(RandomStringUtils.random(8,new char[]{'a','b','c','1', '2', '3'}));
答案 2 :(得分:0)
尝试:
str.charAt(ThreadLocalRandom.current().nextInt(0, str.length()));
答案 3 :(得分:0)
在Java8中
final int length = 8;
final Random rand = new Random();
String random = IntStream.range(0, length).mapToObj(i -> str.charAt(rand.nextInt(100) % str.length()) + "").collect(Collectors.joining());
System.out.println(random);
为10次运行生成的随机字符串
A31CCCB3
1AC3A2CA
BAB11B2A
A33A1ACA
BCCCB2AC
331C12CA
3CC1AAB3
113BAABB
1BC22B1A
31BBCAC1
答案 4 :(得分:0)
您可以使用以下的Utilty类
import java.util.Random;
public class RandomString {
private char[] symbols;
private final Random random = new Random();
private final char[] buf;
public RandomString(int length ,char[] symbols) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
this.symbols = symbols;
}
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}
从您的主要使用
RandomString randString = new RandomString(numChars ,charSet.toCharArray());
for (int i = 0; i < lineNum; i++) {
System.out.println("" +randString.nextString());
}