exception handling java user input

落花浮王杯 提交于 2019-12-12 03:27:28

问题


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.

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.

this is what my code looks like

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();

回答1:


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.

Something like the following will give you the error message properly as you expect.

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();
}



回答2:


Whenever you input a String,reader.hasNextInt() returns false, and the loop terminates. Therefore, not printing anything.

However, since it is a do-while loop, it must execute once, and therefore, if you input a String first, then it prints out the error

This again, only happens if you press Enter after each input



来源:https://stackoverflow.com/questions/43760671/exception-handling-java-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!