Len*_*all 1 java random algorithm
我的文件中有8个名字,每一行只有一个名字.
我试图随意写出其中一个名字.我写了一些代码,但我不知道我将如何继续.(我试图解决这个问题而不使用数组,因为我们还没有学习).我的名单上有这些名字;
patrica
natascha
lena
sara
rosa
kate
funny
ying
Run Code Online (Sandbox Code Playgroud)
而且我想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();
Run Code Online (Sandbox Code Playgroud)
由于您尚未了解数组或列表,因此您需要预先确定要使用的数字,并在到达时停止读取文件.
所以,如果你知道你有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
Run Code Online (Sandbox Code Playgroud)
一旦你学习了Java的技巧,你可以折叠那些代码,虽然它对读者来说变得不那么清楚,所以你可能不应该这样做:
int wordToGet = rnd.nextInt(8);
while ((str = inputCurrent.readLine()) != null && wordToGet-- > 0);
System.out.println(str);
Run Code Online (Sandbox Code Playgroud)