2016-05-01 64 views
3

所以我正在做一個描述生成器,並在「:」分裂一個文本文件。因此,如果文本文件有「dog:fish:cat:bird」,我的代碼會將其拆分爲「:」並隨機選取一個。但是,當我打印出結果時,輸出結果都是一樣的。它會隨機選擇數組中的單詞,但如果我說生成它4次,它將是4次相同的事情。那麼我的邏輯在哪裏是錯誤的如何解決這個問題?我想讓它打印4個隨機不同的東西。我的代碼如下:如何隨機化一個字符串的數組,因此它每次都是不同的循環

公共類發電機 {

public static void main(String[] args) 
{ 
    Scanner scanner = new Scanner(System.in); 
    Random r = new Random(); 

    System.out.print("Enter a file name: "); 
    String fName = scanner.nextLine(); 
    File infle = new File(fName); 
    Scanner read = new Scanner(infle); 

    System.out.print("Enter number to make: "); 
    int things = scanner.nextInt(); 
    System.out.println(); 
    System.out.println("Here are " + things + " things: "); 
    System.out.println(); 


    //gets random animal 
    String animal = read.nextLine(); 
    String[]anm1 = animal.split(":"); 
    int rnd_Animal = r.nextInt(anm1.length); 
    String rndAnimal = (anm1[rnd_Animal]); 


    //gets random adjective 
    String adj = read.next(); 
    String []adj1 = adj.split(":"); 
    int rndAdj = r.nextInt(adj1.length); 
    String randomAdj = (adj1[rndAdj]); 


    for(int i=0; i <things; i++) 
    { 
     System.out.println(randomAdj + " " + rndAnimal);} 

所以,我的輸出將打印這樣的:「汗魚」多次,我輸入了要生成它。如果我輸入3個描述來生成,我怎麼能說出「出汗的魚」,「臭狗」,「慢魚」?感謝您的任何幫助。

+0

我認爲你需要在for循環中放置「獲取隨機動物」和「獲取隨機形容詞」代碼塊。 – Surely

回答

2

問題是你得到的值爲rndAnimalrandomAdj for循環之外。所以它隨機獲得值ONLYCECE並顯示它四次。要解決該問題,請將值分配給循環內的兩個字符串。

for(int i=0; i<things; i++){ 

    //gets random animal 
    String animal = read.nextLine(); 
    String[]anm1 = animal.split(":"); 
    int rnd_Animal =r.nextInt(anm1.length); 
    String rndAnimal =(anm1[rnd_Animal]); 

    //gets random adjective 
    String adj = read.next(); 
    String []adj1 = adj.split(":"); 
    int rndAdj = r.nextInt(adj1.length); 
    String randomAdj = (adj1[rndAdj]); 

    System.out.println(randomAdj + " " + rndAnimal); 
} 
+0

這絕對是。但是,我有一些其他隨機對象在那裏,我得到了「沒有行發現錯誤」。我的隨機對象的順序,nextLine,next,nextLine,nextLine,nextLine,nextLine。我在那裏有一個,因爲它從該陣列中取出兩次,並且我一直在調整nexLine,然後在下一個周圍但似乎無法獲得它。任何想法,即使這聽起來很混亂? –

+0

爲了解決這個問題,我建議你先照顧對象的範圍,然後檢查文本文件。您可能會遇到文件I/O問題,並且您可以尋找解決方案,但是您在問題中提出的問題已經解決。看看它是否有幫助。 – 2016-05-01 07:05:26

+0

進一步檢查您的代碼後,如果我將所有內容放在for循環中,它將從其他行中刪除,這不是我所需要的。它必須從文本文件中隨機選擇僅來自該行的單詞,這就是爲什麼我得到一行未找到錯誤。 –

相關問題