【问题标题】:Java - incompatible types: boolean cannot be converted to intJava - 不兼容的类型:布尔值不能转换为 int
【发布时间】:2018-03-08 11:17:57
【问题描述】:
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

【问题讨论】:

  • reader.hasNextInt() 返回一个布尔值
  • reader.nextInt().
  • hasNextInt() 告诉你是否有一个 int 可以读取。 nextInt 实际检索到令牌。

标签: java


【解决方案1】:

您应该使用reader.nextInt(); 而不是reader.hasNextInt();

但请记住,此方法会引发 3 种类型的错误,应予以处理:

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

【讨论】:

  • 潜在的 InputMismatchException
  • 谢谢,这使程序运行,但我确实得到了 InputMismatchException 和 NoSuchElementException。您对如何处理这些问题有什么建议吗?
  • 你可以使用标准的 try-catch 块来处理它
猜你喜欢
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2015-04-28
  • 1970-01-01
  • 2021-06-19
  • 2019-07-07
相关资源
最近更新 更多