2

I need input from a user to be integer and larger than 10.

Here is my code.

import java.util.*; //program uses class Scanner

public class Tests {

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

        System.out.println("Enter an Integer");

        int weight;
            do {
                while (!input.hasNextInt()) {
                    System.out.println("Please enter an integer!");
                    input.next(); // this is important!
                }
                System.out.println("Enter an Integer >= 10");
                weight = input.nextInt();
            } while (weight < 10);

        System.out.println("OK");

    }

}

My expected output will be to if the weight is integer to print "OK". But my actual output is

Enter an Integer
20
Enter an Integer >= 10
OK

I cannot figure out how to get rid of the "Enter an Integer >= 10" when conditions satisfied.

1
  • 1
    So all you want to do is to avoid printing Enter an Integer >= 10 after the condition is correct ? Commented Feb 2, 2017 at 16:31

4 Answers 4

3

Only print the message if the input does not satisfy the condition.

do {
    while (!input.hasNextInt()) {
        System.out.println("Please enter an integer!");
        input.next(); // this is important!
    }
    weight = input.nextInt();
    if ( weight < 10 ) {
        System.out.println("Enter an Integer >= 10");
    }
} while (weight < 10);
Sign up to request clarification or add additional context in comments.

3 Comments

what's your opinion on, how should the while (!input.hasNextInt()) be processed in the code?
Thank, I was breaking my mind trying to figure out if it is possible to but both conditions as while ((weight < 10) || !input.hasNextInt())
A second question (begginer sorry): the logic f the code is: 1st - execute while (!input.hasNextInt()), or weight = input.nextInt();
1

Use a single while loop that checks a single input at a time. Once you get any input you first verify that it's an integer, the .matches(\d+), if it does match an integer check if the integer is greater than 10, if it's not then ask for an Integer. If all the checks pass then the last else means we got a valid entry from the user.

Scanner input = new Scanner(System.in);
int weight = -1;
String userInput = "";


System.out.println("Enter an Integer: ");
while(weight < 10)
{
    userInput = input.nextLine();
    //check if it's not a digit
    if(!userInput.matches("\\d+"))
    {
        System.out.println("Enter an Integer: ");
    }
    //check if the integer we got is less than 10
    else if(Integer.parseInt(userInput) < 10)
    {
        System.out.println("Enter a Number > 10:");
    }
    //we get here when all conditions are satisfied
    else
    {
        weight = Integer.parseInt(userInput);
    }
}
System.out.println("OK");

Output

Enter an Integer: 
gf
Enter an Integer: 
ytu76
Enter an Integer: 
1
Enter a Number > 10:
20
OK

2 Comments

but can you also explain what's wrong in the current implementation please. Try executing it once.
The original implementation also made sure that the user got a sane answer and another prompt if a non-numeric string was entered. Yours does not.
1

Pavel. Although your question title mentions using a "do-while" loop, the question didn't specify if that's a hard requirement for some reason. I would opt for something like this, without using a do-while:

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

        System.out.println("Enter an Integer");

        int weight;
        while ((weight = readInteger(input)) < 10) {
            System.out.println("Enter an Integer >= 10");
        }
        System.out.println("OK");
        // do something with weight value
    }

    private static int readInteger(Scanner input) {
        while (!input.hasNextInt()) {
            System.out.println("Please enter an integer!");
            input.next(); // this is important!
        }
        return input.nextInt();
    }

Comments

1

Though the answers do suggest the ways to resolve following the algorithm you're looking for and it could be solved with -

 do {
        System.out.println("Enter an Integer >= 10");
        weight = input.nextInt();
    } while (weight < 10);

Yet another interesting point that drew my attention to your code was, how should the following be processed

while (!input.hasNextInt()) { // this block is never reached actually
    System.out.println("Please enter an integer!");
    input.next(); // this is important!
}

and why did the compiler wait for an input without either printing Enter an Integer >= 10 or Please enter an integer!. And found out that's because your method call hasNextInt() awaits your input but would eventually process the next statement once you've provided some integer input (irrespective)(tried 10 and 10 10 as input as well.) The reason being the radix that is getting passed in the input provided would remain default.

Bringing this all out from the Scanner.java in the java.util

/**
 * Returns true if the next token in this scanner's input can be
 * interpreted as an int value in the default radix using the
 * {@link #nextInt} method. The scanner does not advance past any input.
 *
 * @return true if and only if this scanner's next token is a valid
 *         int value
 * @throws IllegalStateException if this scanner is closed
 */
public boolean hasNextInt() {
    return hasNextInt(defaultRadix);
}

JavaDoc for hasNextInt() which in turns calls the overloaded method -


/**
 * Returns true if the next token in this scanner's input can be
 * interpreted as an int value in the specified radix using the
 * {@link #nextInt} method. The scanner does not advance past any input.
 *
 * @param radix the radix used to interpret the token as an int value
 * @return true if and only if this scanner's next token is a valid
 *         int value
 * @throws IllegalStateException if this scanner is closed
 */
public boolean hasNextInt(int radix) {
    setRadix(radix);

JavaDoc for hasNextInt(int radix) which calls the setRadix method.


// The next operation should occur in the specified radix but
// the default is left untouched.
private void setRadix(int radix) {

Couldn't possibly find this in the JavaDoc though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.