2015-11-06 23 views
0

需要我的代碼的一些幫助。我試圖修改書面代碼,要求用戶輸入「是」或「否」,以便循環繼續。如果用戶輸入「yes」或「no」以外的任何內容,我應該使用素數讀取和while循環來顯示錯誤消息。需要幫助修改輸入驗證和錯誤消息的代碼

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    //declare local variables 
    String endProgram = "no"; 
    boolean inputValid; 

    while (endProgram.equals("no")) { 
    resetVariables(); 
    number = getNumber(); 
    totalScores = getScores(totalScores, number, score, counter); 
    averageScores = getAverage(totalScores, number, averageScores); 
    printAverage(averageScores); 
    do { 
     System.out.println("Do you want to end the program? Please enter yes or no: "); 
    input.next(); 
    if (input.hasNext("yes") || input.hasNext("no")) { 
     endProgram = input.next(); 
    } else { 
     System.out.println("That is an invalid input!"); 
    } 
    } 
    while (!(input.hasNext("yes")) || !(input.hasNext("no"))); 
} 
} 
+0

這是我迄今爲止,但它不能正常工作我想看看錯誤是什麼。 –

回答

1

hasNext方法調用不帶任何參數。看看docs

因此,你應該先輸入的值:

String response = input.next(); 

,然後測試響應:

!response.equalsIgnoreCase('yes') || !response.equalsIgnoreCase('no') 

你可以把這個測試進入一個方法,你正在檢查的同樣的事情多次。

通過將endProgram更改爲布爾值可能更容易看到程序的邏輯。也許甚至將它重命名爲running;

boolean running = true; 
... 
while (running) { 
    ... 
    String response; 
    boolean validResponse = false; 

    while (!validResponse) { 
    System.out.println("Do you want to end the program? Please enter yes or no: "); 
    response = input.next(); 
    running = isContinueResponse(response); 
    validResponse = isValidResponse(response); 

    if (!validResponse) System.out.println("That is an invalid input!"); 
    } 
}