user8811407
user8811407

Reputation: 11

How to use a Do-while loop that continuously prompts a user?

(I have a homework question that I've been stuck on that concerns "do-while loops" in Java. )

It is asking me to have a do-while loop that continues to prompt a user to enter a "number less than 100", up until the entered number is actually less than 100.

(It will run three tests:) Ex: Test 1: For the user input 123, 395, 25, the expected output is:

Enter a number (<100): 
Enter a number (<100): 
Enter a number (<100): 
Your number < 100 is: 25

(Here's my code so far:)

public class NumberPrompt {
   public static void main (String [] args) {
   Scanner scnr = new Scanner(System.in);
   int userInput = 0;

      do {
         System.out.println("Enter a number (<100):" );
         System.out.println("Enter a number (<100):" );
         System.out.println("Enter a number (<100):" );
         userInput = userInput + 25;
      } while (userInput > 100);
         System.out.print("");

      System.out.println("Your number < 100 is: " + userInput);
}

(My Output matches exactly with the Test 1 results above, but I realize I'm not setting up the loop right at all because when it does the second test of "-9", the output exactly the same as my first test:)

Enter a number (<100):
Enter a number (<100):
Enter a number (<100):
Your number < 100 is: 25

(This is my first week being introduced to loops, I searched around for some walk through examples but I haven't found many "Do" while loops that remind me of this one. If anyone has some good tips or guides to point me to I would greatly appreciate it.)

Upvotes: 1

Views: 14272

Answers (2)

Al-un
Al-un

Reputation: 3412

1.Reading value

As Juan's comment suggested, you are not reading user input value. Basically, this is done with nextInt() method. Morever, int is a primitive type and must be initialised. You choose the value of 0. So why not choosing 101 so that it starts with an incorrect value? Then you are sure that the while loop will be triggered:

public static void main(String... aArgs) {

    Scanner sc = new Scanner(System.in);
    // initialise at 101 to trigger the while loop
    int userInput = 101;

    // as we start at 101, it will enter the loop at least once
    while (userInput > 100) {
        System.out.println("Enter a number (<100):");
        userInput = sc.nextInt();
    }

    System.out.println("Your number < 100 is: " + userInput);
}

2.Never trust the user

2.1 Exception catching

The above code may be sufficient for your assignement. However, for learning sake, I have a fundamental principal: never trust the user!. If the previous example, if an user inputs azerty, then your program will throw you an InputMismatchException. What's that? This error tells you that the scanner expected an int and you fed him with something else: it throws this up.

A simple analogy is: the scanner can only eat apple. You give him a pear: he takes a bit and throws that up: "I can only eat apple". To prevent your scanner from throwing up, you can ask him: "try a bit, and if this is not an apple, let's try something else"

In code, it gives you something like:

public static void main(String... aArgs) {

    Scanner sc = new Scanner(System.in);
    // initialise at 101 to trigger the while loop
    int userInput = 101;

    // as we start at 101, it will enter the loop at least once
    while (userInput > 100) {
        // tell the scanner to try something
        try {
            System.out.println("Enter a number (<100):");
            userInput = sc.nextInt();
        }
        // if the input is not a number, tell him do this this:
        catch (InputMismatchException e) {
            System.out.println("This is not a number!");
        }
    }

    System.out.println("Your number < 100 is: " + userInput);
}

If you are not familiar with try/catch clause, you can read this

2.1 Scanner feeding

The above code is not working. How? If you enter something which is not a number, like "aaaa", you will have an infinite of

Enter a number (<100):

This is not a number!

Why? Because the scanner did not throw your input out. Basically, he either should eat the pear (but he will throw up) or throw it to the dust bin but you never told him to throw it to the dust bin! The scanner needs to consume the input before trying the next input.

In a nutshell:

  1. userInput starts at 101 so the while loop is entered
  2. You enter aaaa.
  3. The InputMismatchException is caught. The "This is not a number!" is printed out
  4. userInput value did not change (still at 101), so the loop keeps going
  5. At this stage, the scanner did not consume the previous input so the next input is still aaaa.
  6. Go to 3. and start again

How to fix this? By telling the scanner to consume the input with next():

public static void main(String... aArgs) {

    Scanner scnr = new Scanner(System.in);
    // initialise at 101 to trigger the while loop
    int userInput = 101;

    // as we start at 101, it will enter the loop at least once
    while (userInput > 100) {
        // tell the scanner to try something
        try {
            System.out.println("Enter a number (<100):");
            userInput = scnr.nextInt();
        }
        // if the input is not a number, tell him do this this:
        catch (InputMismatchException e) {
            // consume the incorrect input with scnr.next()
            // so that user can enter another input
            System.out.println(scnr.next() + " is not a number!");
        }
    }

    System.out.println("Your number < 100 is: " + userInput);
}

Upvotes: 0

Ahmed Hassan
Ahmed Hassan

Reputation: 11

You don't need to write System.out.println("Enter a number (<100):" ); three times. It will be displayed automatically every time when user inputs value less than 100. And you are assigning value to userInput by your own instead of taking input from user. You should write the code given below.

 do {
     System.out.println("Enter a number (<100):" );
     userInput = scnr.nextInt();
  } while (userInput > 100);
     System.out.println("Your number < 100 is " + userInput);

Upvotes: 1

Related Questions