简体   繁体   English

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

[英]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.

相关问题 java:不兼容的类型:boolean不能转换为int - java: incompatible types: boolean cannot be converted to int Greenfoot / Java - 不兼容的类型:boolean不能转换为int - Greenfoot/Java - incompatible types: boolean cannot be converted to int 错误:类型不兼容:布尔值无法转换为int - error: incompatible types: boolean cannot be converted to int Java : 不兼容的类型; int 不能转换为字符串 - Java : incompatible types; int cannot be converted to string 整数到罗马“不兼容的类型:int 不能转换为布尔值 [在 MainClass.java]” - Integer to Roman "incompatible types: int cannot be converted to boolean [in MainClass.java]" 不兼容的类型,无法转换为 int - Incompatible types, cannot be converted to int 不兼容的类型:int[] 不能转换为 int [in __Driver__.java] - incompatible types: int[] cannot be converted to int [in __Driver__.java] 不兼容的类型:java.lang.String无法转换为布尔值 - Incompatible types: java.lang.String cannot be converted to boolean prog.java:52: 错误:类型不兼容:int 无法转换为布尔值 for(int i=0;i=n/2;i++){ - prog.java:52: error: incompatible types: int cannot be converted to boolean for(int i=0;i=n/2;i++){ JAVA:不兼容的类型:int 无法转换为 java.lang.String - JAVA: Incompatible types: int cannot be converted to java.lang.String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM