简体   繁体   中英

In java, how do I tell a file to choose and print a random word?

Below is my code that I have so far. I only started programming a couple weeks ago so I am new to all of this, and I cannot figure out how to randomly select and print a word. Where do I start?

public static String randomWord(String fileName) 
 throws FileNotFoundException {
    int fileSize = countWords(fileName);
    int N = (int) (fileSize*Math.random());
    Scanner inFile = new Scanner(new File(fileName));
    String word;
    
 
     
  while (inFile.hasNext()) {
     word = inFile.next();
    }
    inFile.close(); 
    return word;
}

Hi so it seems your variable N is the numbered location of the random word you want to find (Also, separate from your question but it is commonplace in java to have all variable names start as lowercase, camelCase is used). There are a few ways you can do this, you could use the while loop you have to place every single word in your file into an array, which would be useful if you wanted to get other random words later, or you could just keep track of what numbered word you are at in the loop itself, and print N-th word when you get to it. As such:

int fileSize = countWords(fileName);
int N = (int) (fileSize*Math.random());
Scanner inFile = new Scanner(new File(fileName));

int count = 0;
while(inFile.hasNext() && count < N) {
      inFile.next();
      count ++;
}
String word = inFile.next();
System.out.println(word);

You can generate Random numbers this way

import java.util.Random; 
Random rand = new Random(); 
int rand_int = rand.nextInt(1000);
System.out.println("Random Integers: "+rand_int); 

Use the random Integer for the selection of random word as index of file in reader. Hopefully it will work

[Note]: This solution is good for practicing purpose but expensive in terms of time-space trade-off, If you are sending a rocket to a moon, just don't copy-paste this code!

For a simpler solution, you can just add these words one by one in an ArrayList and then you can just return a random index.

Here is the sample code:

public static String randomWord(String fileName) 
 throws FileNotFoundException {
    Scanner inFile = new Scanner(new File(fileName));
    ArraList<String> arr = new ArraList<String>();
    String word;
    
 
     
  while (inFile.hasNext()) {
     word = inFile.next();
     arr.add(word);
    }
    inFile.close();

    Random rand = new Random(); //instance of random class
    int upperbound = arr.size();
    //generate random values from 0-(N-1)
    int int_random = rand.nextInt(upperbound);
    return arr.get(int_random);
}

I have not compiled it but let me know if you face any errors executing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM