2016-04-17 63 views
0

我在我的文件中有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(); 

回答

4

由於您尚未學習有關數組或列表的知識,因此您找出你想要的前幾個字,並在你到達時停止閱讀文件。

所以,如果你知道你有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); 
+0

非常好,我喜歡評論。 – nhouser9

+0

@LenaMonikaMarshall沒有辦法直接做到這一點。您必須運行該文件並計算行數。我想你最好的嘗試是將閱讀和計數的過程留給'java.nio.file.Files#readAllLines',儘管這有點超出你的水平。 – Paul

2

您可以簡單地讀取所有的名字,將其存儲在列表中,然後隨機挑選索引:

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

我感謝您的回答,但我是個初學者,我不明白這麼多你的代碼:/這是什麼做的名單? –

+0

正確答案一般,但如果OP尚未學習數組,那麼她可能還沒有了解集合,所以對於提問者級別來說這不是一個有效的答案。 – Andreas