Java - 不兼容的类型:boolean无法转换为int

时间:2018-03-08 11:17:57

标签: java

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);
    }
}

我一直试图让用户输入一些轮次。但轮数必须大于或等于0,因为负数不起作用。有帮助吗?

以下错误代码:

Game.java:11: error: incompatible types: boolean cannot be converted to int
                    numberOfRounds = reader.hasNextInt();
                                                      ^
1 error

1 个答案:

答案 0 :(得分:3)

您应该使用reader.hasNextInt();

而不是reader.nextInt();

但请记住,此方法会抛出应处理的3种类型的错误:

  • InputMismatchException - 如果下一个标记与之匹配 整数正则表达式,或超出范围
  • NoSuchElementException - 如果输入已用尽
  • IllegalStateException - 如果此扫描仪已关闭