Jarrod Nobel Jarrod Nobel - 1 month ago 3
Java Question

Randomize user input based on questions

Im trying to collect some data from a user and display it with the user input. the example i was giving is:

Filename: output.txt
number of lines: 4
Line Length: 8
Character Set: ABC123

2CB3A32C
BB13CAA3
C3A21CB2
CC2B13A3


i currently have gotten the user input but i dont know how to display the random letters and numbers based on the input. Here is my code. Any help would be big.
the data has to be displayed using Loop.

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);
}

}

Answer

Try this.

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();
}
Comments