scanner.nextInt(),超出范围避免?

时间:2013-02-09 08:07:18

标签: java int range java.util.scanner out

我已经完成了一个将十进制数转换为二进制(32bit)的简单程序。如果用户输入溢出数字(2147483647以上的任何内容),我想实现某种类型的错误消息。我尝试了if_else , loop,但很快就发现我甚至不能这样做。所以我把输入作为一个字符串,然后使用像.valueOF()等一些东西搞砸了,似乎仍然无法解决问题。

如果我无法将值存储在第一位,我看不出如何将任何值与a >2147483648进行比较。

以下是我对getDecimal()方法的简单代码:

numberIn = scan.nextInt();

编辑::尝试try / catch方法后,遇到编译错误

"non-static method nextInt() cannot be referenced from a static context"

我的代码如下。

public void getDec()
{
    System.out.println("\nPlease enter the number to wish to convert: ");

    try{
        numberIn = Scanner.nextInt(); 
    }
        catch (InputMismatchException e){ 
        System.out.println("Invalid Input for a Decimal Value");
    }
}      

5 个答案:

答案 0 :(得分:3)

如果下一个令牌无法转换为false,您可以使用Scanner.hasNextInt()方法返回int。然后在else块中,您可以使用Scanner.nextLine()将输入作为字符串读取,并使用相应的错误消息进行打印。就个人而言,我更喜欢这种方法:

if (scanner.hasNextInt()) {
    a = scanner.nextInt();
} else {
    // Can't read the input as int. 
    // Read it rather as String, and display the error message
    String str = scanner.nextLine();
    System.out.println(String.format("Invalid input: %s cannot be converted to an int.", str));
}

实现此目的的另一种方法当然是使用try-catch块。当Scanner#nextInt()方法无法将给定输入转换为InputMismatchException时,integer方法会抛出InputMismatchException。所以,你只需要处理try { int a = scan.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid argument for an int"); } : -

{{1}}

答案 1 :(得分:2)

我建议您使用NumberFormatException的try / catch块包围该语句。

像这样:

try {
  numberIn = Integer.valueOf(scan.next());
}catch(NumberFormatException ex) {
  System.out.println("Could not parse integer or integer out of range!");
}

答案 2 :(得分:0)

使用exceptions ..只要输入的数字超过其存储容量,就会引发异常

请参阅docs.oracle.com/javase/tutorial/essential/exceptions /

答案 3 :(得分:0)

您可以使用hasNextInt()方法来确保有一个可以读取的整数。

答案 4 :(得分:0)

试试这个:

long num=(long)scan.nextLong();
    if (num > Integer.MAX_VALUE){
    print error.
    }
else
int x=(int)num;

或试试catch:

try{
    int number=scan.nextInt()
    }
}catch(Exception ex){
    print the error
    }
相关问题