2015-07-02 36 views
1

我遇到了這部分代碼的問題。該程序要求輸入一對夫婦(姓名,身份證,成績等),然後將結果打印回來。驗證,通知無效,返回循環

我決定從本教程割捨,現在已嫌我的腦袋上一個衆所周知的牆 -

僞什麼,我想在這裏:

Ask user for grade between 9 and 12 
If input is less than 9 or greater than 12, return failed message and -return to loop- 
If input acceptable, continue to next question. 

當前代碼如下:

do { 
    System.out.print("Grade (9-12): "); 
    while (!keyboard.hasNextInt()) { 
     System.out.printf("message saying you're wrong"); 
     keyboard.next(); 
    } 
    userGrade = keyboard.nextInt(); 
} while (userGrade >= 9 || userGrade <= 12); 
+1

你能指定你的代碼有什麼問題嗎?什麼不按預期工作? – JFPicard

+0

那麼,就像現在這樣,這個計劃只是一直停留在要求分數的問題上。我是否投入無效(< 9 or > 12)或有效(9-12)迴應。 –

+0

while(userGrade> = 9 || userGrade <= 12) - 使用&&條件。現在每個數字都會通過(例如5 <= 12) – prsmax

回答

0

的東西嘗試這樣的:

boolean correct = true; 
do { 
    System.out.print("Grade (9-12): "); 
    userGrade = keyboard.nextInt(); 
    if (userGrade < 9 || userGrade > 12) { 
     correct = false; 
     System.out.println("message saying you're wrong"); 
    } else { 
     correct = true; 
    } 
} while (!correct); 
+0

當用戶將寫入'foo'而不是數字時,您不處理大小寫。 – Pshemo

+0

是的,這隻適用於整數值。如果您需要對可能的錯誤進行額外控制,請不要使用nextInt()....使用nextLine()並解析它。 –

+0

這將顯示無效消息並返回到循環(再次詢問),但即使響應在9-12之內,它仍會再次提問。 –

0

我認爲這個問題是在邏輯...

變化

while (userGrade >= 9 || userGrade <= 12); 

到:

while (userGrade >= 9 && userGrade <= 12); 

的||接受高於等於9和低於等於12的任何東西。最後兩個條件使任何整數在條件中都成立。

+0

實際上,它應該是'while(grade <9 || grade> 12)',因爲循環應該繼續,直到給出有效數字 – vefthym

0

您可以將您的任務分成較小的任務。例如創建的helper方法,其

  • 將來自掃描儀讀取直到它找到整數,然後將返回

    public static int getInt(Scanner scanner, String errorMessage){ 
        while (!scanner.hasNextInt()) { 
         System.out.println(errorMessage); 
         scanner.nextLine(); 
        } 
        return scanner.nextInt(); 
    } 
    
  • 或將檢查數量在範圍內(但也只是爲了可讀性)

    public static boolean isInRange(int x, int start, int end){ 
        return start <= x && x <= end; 
    } 
    

所以用這個方法,你的代碼可以像

Scanner scanner = new Scanner(System.in); 
int x; 

System.out.println("Please enter a number in range 9-12:"); 
do { 
    x = getInt(scanner, "I said number. Please try again: "); 
    if (!isInRange(x, 9, 12)) 
     System.out.println("I said number in range 9-12. Please try again: "); 
} while (!isInRange(x, 9, 12)); 

System.out.println("your number is: " + x); 
+0

感謝您的回覆!我應該說我是Java的初學者。我有最少的經驗,但我通常可以接受的東西。我只是試圖做一個簡單的程序並對它進行闡述,看看我能得到多遠(複雜)。我喜歡你將某些任務分解成單獨的方法的建議! –

+0

這些'helper'方法會進入我的main()類中,對嗎? –

+0

是的。但既然我也讓它們公開和靜態,你可以將它們放在你想要的任何類中,然後導入該類。這樣你就可以像'OtherClass.method(data)'一樣使用它們。你也可以使用'import static some.package.with.OtherClass.ourStaticMethod'這樣的靜態導入,並像'ourStaticMethod(data)'一樣使用它。 – Pshemo