异常处理Java用户输入 [英] exception handling java user input

查看:259
本文介绍了异常处理Java用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在代码中添加例外。但它不能完全正常工作。我正在尝试让用户输入整数,然后将其添加到列表中。

I'am trying to put an exception in my code. But it doesnt work fully. Im trying for user to enter integers and then adding it to a list.

为什么它仅适用于第一个输入?说如果我第一次输入1.0,那么它将引发错误。但是如果我说 10,1.0 不会产生错误。当我打印列表时。实际上只有 10 是正确的。但我想这样做,以便如果输入除整数以外的任何内容,则会引发错误,并且不会终止。而是要求用户再试一次。

how come it only works for the first input? say if the first I enter 1.0 then it will raise the error. but if I put say 10, 1.0 it doesnt produce an error. and when i print the list. there is only the 10 well this is actually correct. but i want to make it so that if anything is entered other than integer it raise an error, and does not terminate. instead ask the user to try again.

这就是我的代码

package basic.functions;
import java.util.*;
import java.text.DecimalFormat;

public class Percent {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        reader.useDelimiter(System.getProperty("line.separator"));
        List<Integer> list = new ArrayList<>();
        System.out.println("Enter Integer: ");

        do {
            try {
                int n = reader.nextInt();
                list.add(Integer.valueOf(n));
            } catch (InputMismatchException exception) {
                System.out.println("Not an integer, please try again");
            }
        }

        //When user press enter empty
        while (reader.hasNextInt());
        reader.close();


推荐答案

您正在运行的是一个do-while在检查条件之前执行一次。

What you are running is a do-while which will execute once before checking the condition.

因此,尝试将您的第一个输入解析为处理异常的整数,从而输出错误消息。

So, your first input is tried to be parsed into an integer to which you have handled the exception, thus printing the error message.

如果您在初次以外的任何地方都提供非整数,则代码将在尝试解析输入之前终止循环。

If you give a non-integer anywhere other than first time, your code will just terminate the loop before trying to parse the input.

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    reader.useDelimiter(System.getProperty("line.separator"));
    List<Integer> list = new ArrayList<>();
    System.out.println("Enter Integer: ");

    while (true) {
        try {
            int n = reader.nextInt();
            list.add(Integer.valueOf(n));
        } catch (InputMismatchException exception) {
            System.out.println("Not an integer, please try again. Press enter key to exit");
            if (reader.next().isEmpty()) {
                break;
            }
        }
    }

    System.out.println(list);
    reader.close();
}

这篇关于异常处理Java用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆