なぜwhile文にスローされるエラーはありますか?

gxbe.grxnillo:

次のコードは、エラーがスローされますwhile声明。私は、変数を初期化することを試みたtheInputが、それはエラーが発生し続けています。

public static void main(String[] args) 
{   
    int size = 19;
    int count = 0;
    int theNumber = (int)(Math.random()*(size+1));

    do
    {
        String user = JOptionPane.showInputDialog("Please enter a guess!");
        int theInput = Integer.parseInt(user);
        count++;

        if(theInput < theNumber)
        {
            System.out.println("Guess higher!");
        }
        else if(theInput < theNumber)
        {
            System.out.println("Guess lower!");
        }
        else if(theInput == theNumber)
        {
            System.out.println("Congratulations! You have found the number!");
        }
    } while(**theInput** != theNumber);

}

これは、エラーがスローされます

スレッドの例外「メイン」でjava.lang.Error:未解決のコンパイルの問題:ユーザ入力を変数に解決することはできません

何がこのエラーを引き起こしていますか?

ボブ・ハップ:

問題は、それがtheInputあなたにそれを比較するに着く時間によって範囲外ですtheNumber単純にその宣言と初期化をオフに分割します。

public static void main(String[] args) {   
    int size = 19; // Declare AND initialize
    int count = 0; // Declare AND initialize
    int theNumber = (int)(Math.random()*(size+1)); // Declare AND initialize
    int theInput; // Declare but don't initialize yet

    do
    {
        String user = JOptionPane.showInputDialog("Please enter a guess!");
        theInput = Integer.parseInt(user);
        count++;

        if (theInput < theNumber)
        {
            System.out.println("Guess higher!");
        }
        else if (theInput < theNumber) // Shouldn't this be greater than?
        {
            System.out.println("Guess lower!");
        }
        else if (theInput == theNumber)
        {
            System.out.println("Congratulations! You have found the number!");
        }
    } while (theInput != theNumber);

   }
}

そして、多分あなたは可能性について何かを行う必要がありますNumberFormatExceptionが、それはあなたの教科書に先になっている可能性があります。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=26556&siteId=1