-2

Question 2: As the code is written, if the use inputs a valid integer it asks for "Enter number 2", then "Enter number 3", then sums them. If the user inputs any data other than an integer for any of the entries, the code will print out "Invalid number entered" and only sum the valid integers entered. What I would like to do is force the user to enter only valid integers and the code remain repeating "Enter number X" for that entry until the user does so. Could someone please let me know how this is done? Thanks. Ron

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        int counter = 0;
        int addSum = 0;

        while (counter < 3) {
            counter++;
            int numberEntered = 0;

            System.out.println("Enter number " + counter + " :");

            boolean hasNextInt = myScanner.hasNextInt();

            if (hasNextInt) {
                numberEntered = myScanner.nextInt();

                // myScanner.nextLine(); //why can't myScanner.nextLine()
                // could go here right after the number entered
                // is captured and stored in the numberEntered variable;
                addSum = addSum + numberEntered;
            } else {
                System.out.println("Invalid number entered");
            }
            // myScanner.nextLine only works if placed here before
            // closing of the while loop;
            myScanner.nextLine();
        }
        System.out.println("The sum of the numbers entered are " + addSum);
        myScanner.close();
    }
}
  • You should only ask one question per post. Please [edit] your question to remove one of the questions. – Sweeper May 23 '20 at 14:35
  • Your first question is essentially the same problem as [this](https://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-inputmismatchexception-usi), so I suggest you only leave the second question. – Sweeper May 23 '20 at 14:44

1 Answers1

1

Right now, you are always incrementing the counter no matter what:

while (counter < 3) {
    counter++;

Even when the user enters an invalid number, you increment the counter, causing the loop to run 3 times as usual, hence the current behaviour.

You should only increment the counter when the user enters a valid number:

if (hasNextInt) {
    counter++;
    numberEntered = myScanner.nextInt();

Now you will see that the prompts say "Enter number 0 :", which is probably not desirable. You can fix this by printing (counter + 1) when you are printing the prompt:

System.out.println("Enter number " + (counter + 1) + " :");
Sweeper
  • 145,870
  • 17
  • 129
  • 225