2016-07-31 154 views
1

我想在這裏發生的是讓用戶輸入「開始」。如果用戶輸入開始,則程序必須給出數組中的隨機單詞,然後要求用戶輸入「下一個」,當用戶輸入「下一個」時,程序給出另一個隨機單詞,然後程序要求「下一個」再次輸入,等等......你明白了。我想我的聲明重新執行,如果條件,如果遇到錯誤

這裏是一些代碼,我認爲會產生這種效果,但它是所有打印「類型開始看到一個酷字」 用戶輸入「開始」 然後程序返回任何內容。

任何意見,將不勝感激,如果你能告訴我爲什麼我的代碼這樣做,我會非常感激,因爲這樣我可以從中學習。 感謝

這裏是我寫的代碼:

import java.util.Scanner; 
import java.util.Random; 
public class Words { 
    public static void main(String[]args){ 


     Scanner scan = new Scanner(System.in); 
     String words[] = {"Iterate:","Petrichor:"}; 
     String input = ""; 

     System.out.println("type *start* to see a cool word"); 
     input = scan.nextLine(); 

     while(!input.equals("start")){ 
     String random = words[new Random().nextInt(words.length)]; 
     System.out.println(random); 
     System.out.println(); 
     System.out.println("type *next* to see another cool word"); 
     while(input.equals("next")); 
     } 
    } 
} 

回答

1

你想換你的輸入讀取一個循環:

import java.util.Scanner; 

import java.util.Random; 
public class Words { 
    public static void main(String[]args){ 
    Scanner scan = new Scanner(System.in); 
    String words[] = {"Iterate","Petrichor"}; 
    String input = ""; 

    while (!input.equals("start")) { 
     System.out.println("type *start* to begin"); 
     input = scan.nextLine(); 
    } 

    String random = (words[new Random().nextInt(words.length)]); 
    } 
} 

注意,在你的具體的例子循環條件作品你的if語句,所以不需要if語句。

更新

如果你需要保持這種運行時,用戶類型接下來你可以用裏面的一切一做... while循環,因此至少執行一次:

進口java.util中。掃描器;

import java.util.Random; 
public class Words { 
    public static void main(String[]args){ 
     Scanner scan = new Scanner(System.in); 
     String words[] = {"Iterate","Petrichor"}; 
     String input = ""; 
     do { 
     do { 
      System.out.println("type *start* to begin"); 
      input = scan.nextLine(); 
     } while (!input.equals("start")); 

     String random = (words[new Random().nextInt(words.length)]); 
     System.out.println("type *next* to repeat"); 
     input = scan.nextLine(); 
     } 
    } while (input.equals("next")); 
} 
+0

謝謝你。工作得很好。我真的沒有想到使用!因此如果輸入不是「開始」,則while循環檢查是真實的。 – CapnCoin

+0

我很高興你發現它有幫助,請儘可能將此答案標記爲已接受。 – valarauko

+0

所以添加到這個問題。如果我想讓這個用戶輸入「next」來再次運行整個程序,那麼你會怎麼做? – CapnCoin