Java validate only values between 1 and 3

I am trying to only accept integers between the values of 1 and 3 using a while loop and nested if statement in Java.

Anything outside of this range, produces an error message

The program should only accept integers between 1 and 3, any strings of text or decimal values should also produce the same error message and loop back to the original print statement (enter a number: )

The code below runs without any compiler errors although the statement || (a < 1 || a > 3)) will always produce the error message, regardless of the value.

If I was to delete this statement, the program will run and only accept integers of any value, (error message appearing when a string or decimal value is entered)

Could anyone help range this program, only accepting values of between 1 and 3, thanks.

import java.util.Scanner;

public class Validate { public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int a = 0;

while (true) {
    System.out.print("enter a number: ");


    if (!input.hasNextInt() || !input.hasNext() || (a < 1 || a > 3)) {

        System.out.println("Oops! "); 

        input.nextLine();
    }


    else { 
        a = input.nextInt();
        break;
    }
}
input.close();
System.out.println("a = " + a);


}

}


Make sure to be careful of the order of expressions. If one of the 3 statements you wrote happens to be true then the code in the if curly braces will execute. You likely want something like this

if (!input.hasNextInt() || !input.hasNext()){
    if ((a > 1 || a < 3)){
        YourCode
    }
}

The biggest issue is that you need to remember that initially your integer "a" is set to "0". This always catches your first if condition meaning that a is never set!


You are not updating the value of a , so it's 0 all the time.

import java.util.Scanner;

public class Validate {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int a = 0;
        boolean loop = true;

        while (loop) {
            System.out.print("enter a number: ");

            if (!input.hasNextInt() || !input.hasNext()) {

                System.out.println("Oops! ");
                input.nextLine();
            } else {
                a = input.nextInt();
                if (a <= 3 && a >= 1)
                    loop = false;
                else {
                    System.out.println("Oops! ");
                    input.nextLine();
                }

            }
        }

        input.close();
        System.out.println("a = " + a);

    }
}

EDIT:

链接地址: http://www.djcxy.com/p/68222.html

上一篇: 排序而不复制?

下一篇: Java仅验证1和3之间的值