2017-10-20 92 views
1

我需要用一个while循环来询问用户一个介于1-100之间的数字,并告诉用户输入了错误的号码数字是负数或超过100.这是我迄今为止所拥有的。每当我运行它时,它都会询问用户的输入。当输入为负数或大于100时,表示无效号码,但当用户输入为45时,表示无效号码,当0-100之间的数字有效时。我不认为它读取代码的最后部分。怎么办请问用户输入正确的号码

import java.util.*; 

public class PlayOffs { 
    public static Scanner scan = new Scanner(System.in); 

    public static void main(String[] args) { 

     System.out.print("What is the % chance Team 1 will win (1-99)?: "); 
     int team1input = scan.nextInt(); 
     do { 
      while (team1input >= -1 || team1input >= 101) { 
       System.out.println("That's not between 1-99"); 
       scan.next(); // this is important! 
      } 
      team1input = scan.nextInt(); 
     } while (team1input >= 0 && team1input <= 100); 
     System.out.println("Thank you! Got " + team1input); 
    } 
} 
+2

我真的不明白为什么你需要2个循环 –

+1

此外,你的一些比较是不正确的 – theGleep

+0

@FrankUnderwood内环可能处理案件提供像'富酒吧123'数据时。它会处理'foo'和'bar',然后接受'123'作为有效的号码。代码最有可能基于:[使用java.util.Scanner验证输入](https://stackoverflow.com/q/3059333) – Pshemo

回答

0

你的问题是在你的while循环的这个条件:

while (team1input >= -1 || team1input >= 101) 

45> = -1? => true,这就是为什么它打印无效。

其实你不需要2个循环。在do-while循环就足以让你期望的结果:

import java.util.*; 

public class PlayOffs { 
    public static Scanner scan = new Scanner(System.in); 

    public static void main(String[] args) { 

     System.out.print("What is the % chance Team 1 will win (0-100)?: "); 
     boolean validNumber; 
     int team1input; 
     do { 
      team1input = scan.nextInt(); 
      validNumber = team1input >= 0 && team1input <= 100; 

      if (!validNumber) { 
       System.out.println("That's not between 0-100"); 
      } 

     } while (!validNumber); 
     System.out.println("Thank you! Got " + team1input); 
    } 
} 

运行输出:

什么%的几率1队会赢得(0-100)?: -1
这是不是 0-100 那不是0-100 那就是 不在0-100之间谢谢!得到45

+0

为什么它是(!v​​alidNumber)而不是while(validNumber)? –

+0

你想保持循环,而数字是**不**有效。这是'while(!validNumber)'的作用。当你得到一个有效的号码,那么你可以退出循环。 –

+0

@LuisValdez请阅读:[当某人回答我的问题时该怎么办?](https://stackoverflow.com/help/someone-answers) –

1

您的比较存在问题。
你不需要两个循环。
此代码可能适合。

import java.util.Random; 
import java.util.*; 

    public class PlayOffs { 
     public static Scanner scan = new Scanner(System.in); 

     public static void main(String[] args) { 

      System.out.print("What is the % chance Team 1 will win (1-99)?: "); 
      int team1input = scan.nextInt(); 
      do { 
       if(!(team1input >= 0 && team1input <= 100)) { 
        System.out.println("That's not between 1-99"); 
        scan.next(); // this is important! 
        team1input = scan.nextInt(); 
       } 

      } while (!(team1input > -1 && team1input <101)); 
      System.out.println("Thank you! Got " + team1input); 
     } 
    } 
+0

当您输入45时,将打印出不是有效的数字。检查条件在你的if语句中。 –

+0

U R右 我很想编辑它。 –