我需要使用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);
}
}
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
您的问题出现在您的while循环中:
inputData
45&gt; = -1? =&GT;是的,这就是打印无效的原因。
实际上你不需要2个循环。 do-while循环足以获得所需的结果:
while (team1input >= -1 || team1input >= 101)
运行输出:
第1队将赢的机会是多少(0-100)?: - 1那不是 介于0-100
105之间。这不是介于0-100
101之间 不在0-100
之间45
谢谢!得到了45