简体   繁体   中英

Java loop until user enters a value of 0. The values must be between 1-4 and if over 4, ask user to try inputting again

I need to create a loop where the user can input any amount of numbers between 1-4 and then I calculate the average. Typing 0 will end the program and calculate the average. Any value greater than 4 or less than 0 should not count and ask the user to input the value again. I'm stuck on the last part. I'm not sure if the while loop is the correct loop to use either. Thanks for any help

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double sum = 0;
    double count = 0;

    while(input.hasNextInt()) {
        int num = input.nextInt();
        if (num == 0)
            break;
        if (num > 4)
            System.out.println("Invalid number");
        sum += num;
        count += 1;
    }

    System.out.println("Average: " + sum/count);
}

You will always hit the lines:

sum += num;
count += 1;

Because the code just drops through from the second if statement.

The following would work - note the else if and else blocks will only be executed when the first if drops through:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    double sum = 0;
    double count = 0;

    while(input.hasNextInt()) {
        int num = input.nextInt();

        if (num == 0) {
            break;
        }
        else if (num > 4) {
            System.out.println("Invalid number");
        }
        else {
            sum += num;
            count += 1;
        }
    }

    System.out.println("Average: " + sum/count);
}

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