首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >扫描程序nextInt() -当用户输入整数以外的值时,我是否应该处理此方法抛出的InputMismatchException?

扫描程序nextInt() -当用户输入整数以外的值时,我是否应该处理此方法抛出的InputMismatchException?
EN

Stack Overflow用户
提问于 2016-04-23 08:01:13
回答 2查看 74关注 0票数 0

在使用Scanner类的nextInt()方法时,如果抛出了InputMismatchException,我是否应该通过catch块来处理它?这是一个运行时异常,但由用户输入引起,而不是程序员的错误。

这是我的代码。

代码语言:javascript
复制
package com.sample.programs;

import java.util.InputMismatchException;
import java.util.Scanner;

public class ScannerPractice {

    public static void main(String[] args) {

        readInteger();
    }

    private static void readInteger() {
        // Created a Scanner object
        Scanner input = new Scanner(System.in);

        // Display a prompt text
        System.out.println("Please enter an integer");

        // Accept the input from user
        int number;
        try {
            number = input.nextInt();
            // Display the output to user
            System.out.println("You entered: " + number);
        } catch (InputMismatchException exception) {
            System.err.println("You have entered wrong input. Please enter a number");
            // Log the stack trace
            readInteger();
        } finally {
            input.close();
        }

    }

}
EN

回答 2

Stack Overflow用户

发布于 2016-04-23 08:13:54

是。最好是处理用户错误的输入信标,因为您无法控制或确保用户将正确对齐数据,并且您不能使用readInteger()读取双精度值或字符串。

所以我会处理这个异常。致以问候。

票数 0
EN

Stack Overflow用户

发布于 2016-04-23 08:31:35

不需要,您应该在调用nextInt()之前调用hasNextInt()

这个异常实际上意味着程序员的错误,因为程序员在调用该方法之前忘记了检查有效性。

如果您想再次提示用户,请记住先丢弃错误的输入。

代码语言:javascript
复制
Scanner input = new Scanner(System.in);

int value;
for (;;) {
    System.out.println("Enter number between 1 and 10:");
    if (! input.hasNextInt()) {
        System.out.println("** Not a number");
        input.nextLine(); // discard bad input
        continue; // prompt again
    }
    value = input.nextInt();
    if (value < 1 || value > 10) {
        System.out.println("** Number must be between 1 and 10");
        input.nextLine(); // discard any bad input following number
        continue; // prompt again
    }
    if (! input.nextLine().trim().isEmpty()) {
        System.out.println("** Bad input found after number");
        continue; // prompt again
    }
    break; // we got good value
}
// use value here

// don't close input
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36805023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档