2014-04-26 41 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”你并不需要在那里声明变量,因为你已经宣布它。