2015-09-30 212 views
2

這是我在StackOverflow中的第一個問題,所以我希望你能原諒我在設置這篇文章時可能會遇到的許多錯誤.... 我的問題如下:這段代碼應該生成一個隨機數,將其顯示給用戶(爲了幫助我猜測它沒有做太多的嘗試......這應該只是一個練習),要求用戶猜測0到50之間的數字,檢查輸入是否爲整數,如果用戶猜到正確的數字,則輸出「是,數字是..」。 但是,如果用戶輸入了一個字母或任何不是數字的數字,那麼if/else循環變得瘋狂並且程序開始打印「選擇0到50之間的數字:請插入0到50之間的數字,而不是一個字母「沒有停止... 可以幫助我嗎?Java:在while循環中嵌套一個if/else語句

package methods; 

import java.util.Scanner; 

public class Methods { 

    static int randomNumber; 
    static Scanner userInput = new Scanner(System.in); 

    public static void main(String[] args) { 

     System.out.println(getRandomNum()); 

     int guessResult = 1; 
     int randomGuess = 0; 

     while (guessResult != -1) { 
      System.out.print("Choose a number between 0 and 50: "); 

      if (userInput.hasNextInt()) { 
       randomGuess = userInput.nextInt(); 
       guessResult = checkGuess(randomGuess); 
      } else { 

       System.out.println("Please insert a number, not a letter"); 
      } 

     } 

     System.out.println("Yes, the number is " + randomGuess); 
    } 

    public static int getRandomNum() { 

     randomNumber = (int) (Math.random() * 51); 
     return randomNumber; 

    } 

    public static int checkGuess(int guess) { 

     if (guess == randomNumber) { 

      return -1; 
     } else { 

      return guess; 

     } 
    } 
} 
+1

@ChicagoRedSox它不會幫助算法修改else分支中的guessResult。 – laune

+0

@ChicagoRedSox不會解決他的問題。在提示錯誤後,他想繼續詢問輸入。他需要讀取字符串不讀整數 –

回答

1

你允許用戶輸入一個字母(有意向給了一個錯誤消息,但你只叫scanner.nextInt)

你應該讀取輸入的字符串,然後解析它。

String input = null; 
    while (guessResult != -1) { 
     System.out.print("Choose a number between 0 and 50: "); 

     input = sc.next(); 
     try 
     { 
      randomGuess = Integer.parseInt(input); 
      checkGuess(randomGuess); 
     } catch(NumberFormatException ex) 
     { 
      System.out.println("Please insert a number, not a letter"); 
     } 

    } 
+0

非常感謝!有效!順便說一句,我發現這篇文章是重複的,我很抱歉,我應該刪除它嗎? –