0

I would like my code to pick a random line from my text files.

if (character == 1) { 
  Scanner inputFile = new Scanner(generalcharacters);
  System.out.println("Your character is " + inputFile.nextLine());
  }

Right now I can only figure out how to have it read the "next line" of the text file but the line outputs the same thing every run. How can I make this selection random?

I have looked through the thread of How to get a random line of a text file in Java? SEVERAL times and it doesn't work for me. I tried to use their methods and it printed out several lines of the file instead of one.

When I try to use

if (character == 1) {
   String result = null;
 Random rand = new Random();
 int n = 0;
 for(Scanner sc = new Scanner(fictionalcharacters); sc.hasNext(); )
 {
    ++n;
    String line = sc.nextLine();
    if(rand.nextInt(n) == 0)
       result = line;
       System.out.println(line);         
 }
 }    

It prints out the whole list of characters, not just one.

Beth.Bae
  • 1
  • 1

0 Answers0