简体   繁体   中英

How to repeat until the user enters an integer?

This is currently my code. What I want it to do, is accept up to 10 numbers in an array then do and display some math for them. What I managed to do, is catch errors, then stop the program. What I want it to do, is keep the program running until the user correctly enters an integer. I managed to do something similar for my y/n string, but I don't know how to do it for integer arrays.

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    int i=0, numberlist[] = new int [10];
    String yn=null;

        while (i < 10)
    {
        try {
            System.out.print("Please enter your number\n");
            numberlist[i]=input.nextInt();
            System.out.print("Would you like to enter another number? (y/n)\n");
            yn=input.next();
            i++;
                        if (i==10)  
                            {System.out.println("You reached the maximum amount of numbers\n");
                            break;}

                        if (yn.equals("n"))
                            break;

                        else if (!yn.equals("y"))

                            while (true)
                                {System.out.print("Please only enter a 'y' for yes or 'n' for no next time.\nDo you understand? Type 'y' to continue\n");
                                yn=input.next();
                                    if (yn.equals("y"))
                                        break;
                                }


            }catch (Exception e){System.out.println("Please enter the correct number(integers only) next time.");}
}

    int max=numberlist[0], min=numberlist[0], numlength = i, sum=0;
    float average;

    for(i = 0; i < numlength; i++) {
        if(numberlist[i] > max)
            max = numberlist[i];            
    }

    for(i = 0; i < numlength; i++) {
        if(numberlist[i] < min)
            min = numberlist[i];
    }

    for(i = 0; i < numlength; i++) {
        sum=numberlist[i]+sum;
    }
    average = (float)sum/(float)numlength;

    System.out.println("Your Sum is: "+sum);
    System.out.println("Your Average is: "+average);
    System.out.println("Your Maximum is: "+max);
    System.out.println("Your Minimum is: "+min);
}

Move your error handling for numbers inside the while loop so that any exceptions don't break the flow out of the loop and end the program.

while (i < 10) {
    try {
        System.out.print("Please enter your number\n");
        numberlist[i] = input.nextInt();
        System.out.print("Would you like to enter another number? (y/n)\n");
        yn = input.next();
        i++;
        if (i == 10) {
            System.out.println("You reached the maximum amount of numbers\n");
            break;
        }

        if (yn.equals("n"))
            break;
        else if (!yn.equals("y"))
            makeUserUnderstand(input,
                    "Please only enter a 'y' for yes or 'n' for no next time.");

    } catch (InputMismatchException e) {
        makeUserUnderstand(input,
                "Please enter the correct number (integers only) next time.");
    }
}

I've moved out the common "Do you understand?" part into a method.

private static void makeUserUnderstand(Scanner input, String msg) {
    while (true) {
        System.out.println(msg);
        System.out.println("Do you understand? Type 'y' to continue\n");
        if (input.next().equals("y"))
            break;
    }
}

First of all, don't catch Exception. You should catch only the specific exceptions that you care about and know might occur in your code. Any other exceptions indicate a serious problem and by catching them, you can accidentally squelch important information that indicates a bug that needs your attention.

With that said, you can solve your problem by making your try block smaller by only wrapping the code that reads input. In addition, create a loop that checks a flag that indicates if an error occurred. The flag can be set in the catch block when an error occurs parsing the input into an integer.

If you have trouble translating my description into code, feel free to ask about the details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM