【问题标题】:In java, how do I tell a file to choose and print a random word?在java中,如何告诉文件选择并打印一个随机单词?
【发布时间】:2020-07-06 04:29:22
【问题描述】:

以下是我到目前为止的代码。我几周前才开始编程,所以我对这一切都很陌生,我不知道如何随机选择和打印一个单词。我从哪里开始?

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

【问题讨论】:

  • 目前您总是返回文件中的最后一个单词,但您想返回Nth 单词,对吗?你能想出一个在Nth 字上停下来的方法吗?

标签: java file random word


【解决方案1】:

您好,看来您的变量 N 是您要查找的随机单词的编号位置(另外,与您的问题不同,但在 java 中,所有变量名称都以小写开头,camelCase 是用过的)。有几种方法可以做到这一点,您可以使用 while 循环,您必须将文件中的每个单词放入一个数组中,如果您想稍后获取其他随机单词,这将很有用,或者您可以只跟踪你在循环本身中的编号单词,并在你到达它时打印第 N 个单词。因此:

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

【讨论】:

    【解决方案2】:

    您可以通过这种方式生成随机数

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

    使用随机整数选择随机单词作为阅读器中的文件索引。希望它会工作

    【讨论】:

    • 问题已经有一个正确生成的随机数。
    【解决方案3】:

    [注意]:此方案适合练习目的,但在时空权衡方面代价高昂,如果您要向月球发射火箭,请不要复制粘贴这段代码!

    对于更简单的解决方案,您可以将这些单词一一添加到 ArrayList 中,然后您可以返回一个随机索引。

    这里是示例代码:

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

    我还没有编译它,但如果你在执行它时遇到任何错误,请告诉我。

    【讨论】:

    • 这里需要权衡时间/空间。可以遍历文件两次,比较耗时,也可以第一次存储,比较占用内存。
    • 如果您知道您的文件不会太大,或者如果您从同一个文件中选择许多随机单词,那么以空间换时间可能是一个很好的选择。但这是一种权衡。
    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多