繁体   English   中英

如何从txt文件中选择一个随机单词?

[英]How to select a random word from a txt file?

我有一种方法需要从txt文件中选择一个随机单词,但它仅在某些时间有效。

该文件的内容如下:

Broccoli
Tomato
Kiwi
Kale
Tomatillo

我的代码:

import java.util.Random; 
import java.util.Scanner; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException;

public String getRandomItem(){
    Scanner fileIn = null;

    String temp = ""; 
    int r = randomGenerator.nextInt(5) + 1; 
    byte i = 0;

    try {
        fileIn = new Scanner(new FileInputStream("bundles.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        System.exit(0);
    } 

    while(i <= 5){
        temp = fileIn.nextLine();

        if(i == r){ 
            break;  
        }

        i++;
    }

    fileIn.close();

    return temp; 
}

有人可以告诉我我要去哪里错吗?

我将使用Files.readAllLines(Path)一次读取所有行,然后从中获取一个随机单词。 就像是,

private static List<String> lines = null;
static {
    try {
        lines = Files.readAllLines(new File("bundles.txt").toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private Random rand = new Random();

public String getRandomItem() {
    return lines.get(rand.nextInt(lines.size()));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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