我有一个问题,我似乎无法修复。我的目标是提示用户玩游戏的人数。我想继续提示用户,而他们的输入满足以下要求: - 输入不是整数 - 输入不足三人 - 输入比有七个||在while循环不按预期工作
较大的正在发生的事情是,它似乎需要3输入检查第三种情况,一种为第一种,二种为第二种。它并不是一次检查它们,我认为它与语法.nextInt()有关,但是我找不到另一种表达方式。提前感谢您的帮助!
下面是代码:
public void setNumPlayers(Game game) {
Scanner input = new Scanner(System.in);
System.out.println("How many people are playing?");
while(!input.hasNextInt() || input.nextInt() < 3 || input.nextInt() > 7) {
System.out.println("Please eneter the number of people playing. You must have at least three players, and no more than seven.");
input.next();
}
game.setNumPlayers(input.nextInt());
input.close();
}
,并在主
Game g = new Game();
ConsoleOutput io = new ConsoleOutput();
io.setNumPlayers(g);
System.out.println(g.getNumPlayers());
编辑电话:我已经改变了代码到nextInt存储为一个变量 。下面的代码起作用,如果我输入字母会提示我,提示我并让我重新分配x,如果我在参数外输入一个数字,唯一的问题是如果我输入了一个不正确的数字,那么它就会崩溃。我应该把它封装在某种try/catch中吗?这似乎并不实际。
public void setNumPlayers(Game game) {
Scanner input = new Scanner(System.in);
System.out.println("How many people are playing?");
while(!input.hasNextInt()) {
System.out.println("Please eneter the number of people playing.");
input.next();
}
int x = input.nextInt();
while(x<3 || x>7) {
System.out.println("The number of players must be at least three and no more than seven.");
x = input.nextInt();
}
game.setNumPlayers(x);
input.close();
}
将'nextInt()'赋值给一个变量。当你两次调用nextInt()时,你会得到不同的结果。 – khelwood 2015-03-02 11:29:17