0

我已经完成了一个将十进制数转换为二进制数的简单程序(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");
    }
}      
4

5 回答 5

3

如果下一个标记无法转换为 ,您可以使用Scanner.hasNextInt()返回 的方法。然后在块中,您可以将输入读取为字符串,并使用适当的错误消息将其打印出来。就个人而言,我更喜欢这种方法:falseintelseScanner.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");
}
于 2013-02-09T08:11:46.127 回答
2

我建议你用 try/catch 块包围该语句NumberFormatException

像这样:

try {
  numberIn = Integer.valueOf(scan.next());
}catch(NumberFormatException ex) {
  System.out.println("Could not parse integer or integer out of range!");
}
于 2013-02-09T08:11:42.867 回答
0

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

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

于 2013-02-09T08:12:06.467 回答
0

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

于 2013-02-09T08:12:25.217 回答
0

尝试这个 :

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

或尝试捕捉:

try{
    int number=scan.nextInt()
    }
}catch(Exception ex){
    print the error
    }
于 2013-02-09T08:13:29.670 回答