我是Java新手,我有一个小问题,希望大家能帮帮我。 我有一个Names.txt文件,其中包含大量随机名称,每行都有一个适当的名称 (爆炸: 俊 米歇尔 安东尼 等等...) 我一直在编写一个随机选择以下名称之一的函数:
public static void RandomNameGenerator() throws FileNotFoundException
{
// the File.txt has organized names, meaning that each line contains a name
//the idea here is to get a random int take that number and find a name corresponding to that line number
int txtnumlines = 0; // how many lines the txt file has
Random random = new Random();
Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
while (file.hasNext()) //counts the number of lines
{
file.nextLine();
txtnumlines += 1;
}
int randomintname = random.nextInt(txtnumlines);
// takes a random number, that number will be used to get the name from the txt line
String RandomName = "";
// I'm stuck here :(
}
问题是我不知道如何继续,更具体地说,如何使用我代表随机行的随机整数提取名称(比如alex)
希望我的问题很清楚, 谢谢您的帮助!
答案 0 :(得分:0)
在这里,您可能想尝试一下:
public static void RandomNameGenerator() throws FileNotFoundException
{
// the File.txt has organized names, meaning that each line contains a name
//the idea here is to get a random int take that number and find a name corresponding to that line number
int txtnumlines = 0; // how many lines the txt file has
Random random = new Random();
Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
Scanner fileReloaded = new Scanner(new File("Names.txt")); //Let's use another one since we can't reset the first scanner once the lines have been counted (I'm not sure tho)
while (file.hasNext()) //counts the number of lines
{
file.nextLine();
txtnumlines += 1;
}
int randomintname = random.nextInt(txtnumlines);
// takes a random number, that number will be used to get the name from the txt line
int i = 0;
String RandomName = "";
while(fileReloaded.hasNext())
{
String aLine = fileReloaded.nextLine();
if (i == randomintname) Randomname = aLine;
i++;
}
// Now you can do whatever you want with the Randomname variable. You might want to lowercase the first letter, however. :p
}
答案 1 :(得分:0)
阅读所有行
String[] lines = new Scanner(
MyClass.class.getClassLoader().getResourceAsStream("Names.txt"),
StandardCharsets.UTF_8.name()
).next().split("\\A");
提取随机行
Random random = new Random();
String randomLine = lines[random.nextInt(lines.length)].trim();