[英]I need to type number 2 times after my scanner scan the input
Could you help me to understand why I need to type 2 times to allow scanner to scan my input data.你能帮我理解为什么我需要输入 2 次才能让扫描仪扫描我的输入数据。 What I am basically check in below piece of code is to validate if number is a int type and is above 0 to ask number of players playing the game (guessing number game)
我在下面这段代码中基本上检查的是验证数字是否为 int 类型并且大于 0 以询问玩游戏的玩家数量(猜数字游戏)
Validation code works perfectly fine but...I need to type digit 2 times...验证码工作正常,但是...我需要输入数字 2 次...
package pakiet;
import java.util.Random;
import java.util.Scanner;
public class GraModyfikacjaLiczbyGraczy {
public static void main(String[] args) {
Random rand = new Random();
int los = rand.nextInt(11);
int liczbaGraczy; // number of players
Scanner scan7 = new Scanner(System.in); // zamknac
System.out.println("Type number of players");
while (!scan7.hasNextInt() || scan7.nextInt() < 0) {
System.out.println("Type number of players");
scan7 = new Scanner(System.in);
}
liczbaGraczy = scan7.nextInt();
You initialize Scanner
2 times thats why -你初始化
Scanner
2 次,这就是为什么 -
In while loop -在while循环中 -
while (!scan7.hasNextInt() || scan7.nextInt() < 0) {
System.out.println("Type number of players");
//Issue here
scan7 = new Scanner(System.in);
}
You can simply use scan7.next()
for next input.您可以简单地使用
scan7.next()
进行下一个输入。
You can use do-While
loop properly to achieve this -您可以正确使用
do-While
循环来实现这一点 -
public static void main(String[] args) {
Random rand = new Random();
int los = rand.nextInt(11);
int liczbaGraczy; // number of players
Scanner scan7 = new Scanner(System.in); // zamknac
System.out.println("Type number of players");
do {
while (!scan7.hasNextInt()){
System.out.println(" Type number of players :");
scan7.next();
}
liczbaGraczy = scan7.nextInt();
}while (liczbaGraczy < 0);
System.out.println("Number of players :"+liczbaGraczy);
}
Hope this will help.希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.