**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。
这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
3天前关闭。
Improve this question
我需要验证输入,但不确定如何在代码中正确地执行此操作。我需要确保teamSize介于9和15之间,并且players大于1
import java.util.Scanner;
public class SoccerTeam {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many players do you wish per team?");
System.out.println("(Enter a value in the range 9 - 15): ");
int teamSize = scan.nextInt();
while (teamSize < 9) {
System.out.println("Number of players Invalid. \nHow many players do you wish per team?");
System.out.println("(Enter a value in the range 9 - 15): ");
}
System.out.println("How many players are available?");
int players = scan.nextInt();
while (players < 1) {
System.out.println("Number of players Invalid. \nHow many players are available?");
}
int teams = players / teamSize;
int leftOver = players % teamSize;
System.out.println("There will be " + teams + " teams with " + leftOver + " players left over.");
}
}
3条答案
按热度按时间gopyfrb31#
对于
teamSize
,可以使用||(OR)运算符,用于验证是否必须再次询问该值是小于9还是大于15。因此,您可以使用以下方法添加该值:对于
players
,验证操作是可以的,只要记住再次请求该值,否则while
将进入无限循环:就是这样!
ogq8wdun2#
我喜欢用这样的句型反复问问题并得到答案:
wydwbb8l3#
如果用户输入是无效的,则必须确保用户可以输入新值。要为
teamSize
或players
输入新值,应在while循环中使用scan.nextInt()
初始化变量,而不是之前。注意:由于Java的变量作用域规则,变量仍然必须在while循环外声明,以确保循环后的可访问性,这一点很重要。