我的文件中有8个名称,每一行只有一个名称。
我想随便写一个名字。我已经编写了一些代码,但我不知道我将如何继续。(我试图在不使用数组的情况下解决这个问题,因为我们还没有学习)。我的名单上有这些名字;
patrica
natascha
lena
sara
rosa
kate
funny
ying我想用system.out.println随机写出一个名字
这是我的代码:
BufferedReader inputCurrent = new BufferedReader(new FileReader("aText.txt"));
String str;
int rowcounter =0;
int mixNum =0;
String strMixNum=null;
while((str = inputCurrent.readLine())!= null){
rowcounter++;
mixNum = rnd.nextInt(rowcounter)+1;
//strMixNum = ""+strMixNum;
String str2;
while((str2 = inputCurrent.readLine())!= null){
// i dont know what i s shall write here
System.out.println(str2);
}
}
inputCurrent.close();发布于 2016-04-17 22:49:56
因为您还没有了解数组或列表,所以您可以先找出您想要的数字单词,并在到达时停止读取该文件。
所以,如果你知道你有8个单词,你就这样做:
int wordToGet = rnd.nextInt(8); // returns 0-7
while ((str = inputCurrent.readLine()) != null) {
if (wordToGet == 0)
break; // found word
wordToGet--;
}
System.out.println(str); // prints null if file didn't have enough words一旦您了解了Java的诀窍,您就可以折叠代码,尽管对读者来说它变得不那么清晰了,所以您可能不应该这样做:
int wordToGet = rnd.nextInt(8);
while ((str = inputCurrent.readLine()) != null && wordToGet-- > 0);
System.out.println(str);发布于 2016-04-17 22:41:18
您可以简单地读取所有的名称,将它们存储在列表中,然后随机选择一个索引:
List<String> names = Files.readAllLines(Paths.get("aText.txt"));
// pick a name randomly:
int randomIndex = new Random().nextInt(names.size());
String randomName = names.get(randomIndex);
System.out.println(randomName);https://stackoverflow.com/questions/36682992
复制相似问题