2015-11-07 83 views
0

我试图让用户在0到10之间输入任意数量的无限次数,直到他们想要停止。他们通过输入值-1来停止。到目前为止,我已经能够创建当他们输入正确的值时发生了什么,但是当他们输入-1(在while循环中这是一个无效值)时,程序知道它是无效的。我要找的所有程序都是为了排除可能的无效输入而排除-1,并使程序停止询问更多输入。这里是我到目前为止的代码:如何获取用户输入的数字以退出循环?

int userInput=0; 
    System.out.println("Please enter numbers ranging from 0 to 10 (all inclusive)."); 
    System.out.println("When you want to stop, type and enter -1."); 


    while (userInput <= 10 && userInput >= 0) 
    { 
     userInput=Integer.parseInt(br.readLine()); 

     while (userInput > 10|| userInput < 0) 
     { 
      System.out.println("That number is not in between 0 and 10. Please enter a correct number."); 
      userInput=Integer.parseInt(br.readLine()); 
     } 
     sum=sum+userInput; 
     freq++; 
    } 
    while (userInput == -1) 
    { 
     System.out.println("You have chosen to stop inputing numbers."); 
    } 

对不起,我有限的了解:/

回答

0

我建议你试图做太多与while循环。正如它所写,你永远不会摆脱你的第一个。如果输入0到10之间的数字,它会返回并再次询问。如果你把其他的东西放在其他东西里面,你可以点击那个嵌套的while循环,然后它会再次询问一个数字。考虑流量和你想要它做什么。这里有一个简单的方法去看看它:

System.out.println("Please enter numbers ranging from 0 to 10 (all inclusive)."); 
System.out.println("When you want to stop, type and enter -1."); 
keepgoing = true; 
while(keepgoing) { 
    userInput=Integer.parseInt(br.readLine()); 
    if((userInput <= 10 && userInput >= 0) { 
     sum=sum+userInput; 
     freq++; 
    } 
    else if(userInput == -1) { 
     System.out.println("You have chosen to stop inputing numbers."); 
     keepgoing = false; 
    } 
    else { 
     System.out.println("That number is not in between 0 and 10. Please enter a correct number."); 
    } 
} 

至少我认为它到达那里。有很多方法可以控制代码的流向。知道何时使用哪一个是很好的。

相关问题