【发布时间】:2018-04-01 23:05:59
【问题描述】:
我需要使用一个 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 个循环
-
另外,你的一些比较是不正确的
-
@FrankUnderwood 内循环可能会处理提供像
foo bar 123这样的数据的情况。它将处理foo和bar,然后接受123作为有效数字。代码最可能基于:Validating input using java.util.Scanner -
@Luis 你发布了你的代码,但没有描述它的问题。使用edit 选项来澄清您的问题。
-
@Pshemo 可能。好像没有合适的描述。因此,可以以多种方式解释代码。
标签: java loops input while-loop