2014-04-26 42 views
0

我正在嘗試定義一個詢問用戶輸入(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」,我不能再這樣做內循環。我認爲我的問題非常簡單,但我找不出解決該問題的方法。有誰知道如何?

+0

你的問題沒有意義。你爲什麼擔心重新定義'x'?問題是什麼?錯誤信息?意外的輸出? – Daniel

回答

0

如果退出循環的條件是輸入負值3次,則將其用作實際條件。代碼應該更易於閱讀。

incorrectAttempts = 0; 

while (incorrectAttempts < 3) 
{ 

get new value 

value invalid? 
yes: incorrectAttempts = incorrectAttempts + 1; 
no: do anything else; 
} 
1

它看起來像這可能工作,如果你只是從線12.刪除「INT」你並不需要在那裏聲明變量,因爲你已經宣佈它。