Testing if an input is Integer and larger than (two conditions) with do-while loop - Java

房东的猫 提交于 2019-12-11 03:37:12

问题


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:


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);



回答2:


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



回答3:


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();
    }



回答4:


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.



来源:https://stackoverflow.com/questions/42007352/testing-if-an-input-is-integer-and-larger-than-two-conditions-with-do-while-lo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!