[英]Java - incompatible types: boolean cannot be converted to int
import java.util.Scanner;
import java.lang.Object;
public class Game {
public static void main(String[] args) {
int numberOfRounds = -1;
while (numberOfRounds <= -1) {
Scanner reader = new Scanner(System.in);
System.out.print("Please input the number of rounds. The number of rounds must be greater than or equal to 0: ");
numberOfRounds = reader.hasNextInt();
reader.close();
}
System.out.println("number is" + numberOfRounds);
}
}
I've been trying to get the user to input a number of rounds. 我一直试图让用户输入一些轮次。 But the rounds have to be greater than or equal to 0, because negative numbers do not work. 但轮数必须大于或等于0,因为负数不起作用。 Any help? 有帮助吗?
Error code below: 错误代码如下:
Game.java:11: error: incompatible types: boolean cannot be converted to int
numberOfRounds = reader.hasNextInt();
^
1 error
Instead of using reader.hasNextInt();
而不是使用reader.hasNextInt();
you should use reader.nextInt();
你应该使用reader.nextInt();
But remember that this method throws 3 types of errors which should be handled: 但请记住,此方法会抛出应处理的3种错误:
InputMismatchException
- if the next token does not match the Integer regular expression, or is out of range InputMismatchException
- 如果下一个标记与Integer正则表达式不匹配,或者超出范围 NoSuchElementException
- if input is exhausted NoSuchElementException
- 如果输入用尽 IllegalStateException
- if this scanner is closed IllegalStateException
- 如果此扫描程序已关闭
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.