【问题标题】:scanner.nextInt(), out of range avoidance?scanner.nextInt(),避免超出范围?
【发布时间】:2013-01-25 00:30:34
【问题描述】:

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

如果我一开始就无法存储值,我不知道如何将任何值与a >2147483648 进行比较。

这是我为 getDecimal() 方法提供的裸代码:

numberIn = scan.nextInt();

Edit:: 尝试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");
    }
}      

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    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
        }
    

    【讨论】:

    • 这永远行不通。 scan.nextInt() 返回一个 int,它永远不会超过 MAX_VALUE
    【解决方案2】:

    如果下一个令牌无法转换为int,您可以使用Scanner.hasNextInt() 方法,该方法返回false。然后在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() 方法无法将给定的输入转换为integer 时,它会抛出InputMismatchException。所以,你只需要处理InputMismatchException:-

    try {
        int a = scan.nextInt();
    } catch (InputMismatchException e) {
        System.out.println("Invalid argument for an int");
    }
    

    【讨论】:

    • +1 好的解决方案,除了try-catch,我们还能做什么?
    • 感谢您的快速回复!我决定先尝试 .hasnextInt(),但遇到“无法从静态引用非静态方法”上下文错误。
    • @StephenGilardi.. 你如何以及在哪里使用它?你能展示你的代码吗?
    • @Rohit Jain.. 我确实使用了与您完全相同的上下文,但我用我已经初始化为 int 的变量“numberIn”替换了“int a”。
    • @StephenGilardi.. 可能你的变量numberIn 是一个静态变量。没有看到你的实际代码就说不清楚。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        我建议您在该语句周围加上 NumberFormatException 的 try/catch 块。

        像这样:

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

        【讨论】:

        • 我收到编译错误。 “不能从静态上下文中引用非静态方法 nextInt()”
        • @StephenGilardi 在这个例子中我没有使用 nextInt 。 Here 是 ideone 上的一个工作示例。我猜你是在 main 中调用它,而 Scanner 不是类中的静态变量,对吧?如果是这样,请移动扫描仪主体或使其静止。
        • 没有。这是它自己的“十进制”类。我在 Driver 类中有 main 。不过,我会调查你在最后一部分所说的内容
        • 啊我从来没有注意到你没有使用 nextInt。这完美无缺。这不像其他(潜在的?)解决方案那样有意义(逻辑上)。也是我第一次被介绍到 try/catch。不过感谢您的帮助!
        猜你喜欢
        • 1970-01-01
        • 2018-06-18
        • 2016-07-22
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2017-05-22
        • 2023-04-07
        • 2023-03-27
        相关资源
        最近更新 更多