gpt4 book ai didi

Java - 不兼容的类型 : boolean cannot be converted to int

转载 作者:行者123 更新时间:2023-11-29 04:21:03 51 4
gpt4 key购买 nike

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

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

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

关于Java - 不兼容的类型 : boolean cannot be converted to int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49171820/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com