2014-04-23 25 views
1

我有这种情况:用户必须为'x'输入一个数字。如果值为>=0,则使用此坐标创建新游戏。如果用户输入负数,则会显示一条消息,他将有另一次机会,将有三次机会输入正确的号码,否则将不会有任何游戏。我为这种情况尝试了一个'if-statement',但它运行不正常。循环内部是否有这样的方法?需要一个循环来重复3次以处理特殊情况

+5

安置自己尝试代码 – newuser

+1

你需要一个变量来跟踪的多少更多的尝试则允许用户。 –

+0

你到目前为止做了什么? –

回答

3
final static int NUMBER_OF_TRIES = 3; 
boolean correctNumber = false; 
int attemptNumber = 0; 

while (!correctNumber) 
{ 

    //get user input 

    if (inputIsCorrect) 
    { 
     createANewGame(); 
     correctNumber = true; 
    } 
    else 
    { 
     System.out.println("Incorrect answer"); 
     attemptNumber++; 
    } 

    if(!inputIsCorrect && attemptNumber == NUMBER_OF_TRIES) 
    { 
     System.out.println("You have reached the max number of tries"); 
     System.exit(0); //or whatever you want to happen 
    } 

} 
+0

for循环会更清洁吗? – DonyorM

+0

也可以使用for循环,但它们本质上看起来是一样的,唯一的区别是您可以删除attemptNumber变量,如果输入正确,则使用break语句。在这种情况下,我个人比较喜欢while循环,因为它似乎更适合于试图完成的任务。这真是一个偏好问题。 – yitzih

+0

非常感谢!这对我来说似乎很不错。唯一不能理解的是:我必须要求用户输入'x',以便我声明,如果答案错误,他必须再次输入。我怎样才能做到这一点,而无需再次更改变量?因为它已被定义(int x = keyboard.nextInt(); keyboard.nextLine();)。 – user3563945

0

您可以使用for循环用下面的代码

for(int x = 0; x < 3; x++) { 
    //Perform logic 
} 

这将正好运行三次。您可以更改3以使其运行次数更多或更少。

+3

你不觉得这会循环4次吗? –

+0

@FlorescentTicker感谢捕捉那* *羞怯的笑容* – DonyorM

+0

如果您使用x <3它运行3次,并包括3以显示它将运行的频率 – LionC

0
 import java.util.Scanner; 

    boolean isValidInput=false; 
    int counter=0; 

    Scanner sc = new Scanner(System.in); 
    int userInput; 

    while(counter<3 && isValidInput==false) 
    { 
     System.out.println("Enter a value: "); 
      userInput = sc.nextInt(); 

     if(userInput>=0) 
      isValidInput=true; 

     else 
      System.out.println("Please Enter valid input"); 

     counter++; 

    } 
相关问题