我正在嘗試定義一個詢問用戶輸入(x)的主要方法。如果該值大於等於0,它會要求另一個輸入(y)。但是,如果該值爲< 0,則玩家有三次機會輸入正確的值,否則他退出遊戲。這是我到現在爲止:需要更新while循環中的變量
Scanner keyboard = new Scanner(System.in);
final int NUMBER_OF_TRIES = 3;
boolean correctNumber = false;
int attemptNumber = 0;
int x = keyboard.nextInt();
keyboard.nextLine();;
while (x < 0)
{
System.out.println("Must not be negative.");
System.out.print("Initial x: ");
int x = keyboard.nextInt(); keyboard.nextLine();
if (x >= 0)
{
correctNumber = true;
}
else
{
System.out.println("Incorrect answer");
attemptNumber++;
}
if(x < 0 && attemptNumber == NUMBER_OF_TRIES)
{
System.out.println("Too many errors. Exiting.");
break;
}
但正如我已經定義的「X」,我不能再這樣做內循環。我認爲我的問題非常簡單,但我找不出解決該問題的方法。有誰知道如何?
你的問題沒有意義。你爲什麼擔心重新定義'x'?問題是什麼?錯誤信息?意外的輸出? – Daniel