简体   繁体   中英

I want to loop while in Java until user inputs the Right value but I am not able to do

I want user to input the right value and loop the request until user does the same. But This code is not working, Can anyone correct me? Please help.

public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int a, b;
        b= 0;

        System.out.print("Write something here: ");
        a = scan.nextInt();

       // I want user to input 1 or 2 only, The code should Loop until User inputs 1 or 2
        for (a=0; a<1 && a>2;){
            b++;
            System.out.println("Hello "+ b);
            a = scan.nextInt();
        }
    }

In your for conditional, you're checking whether a is smaller than 1 AND larger than 2. That's obviously never the case, so the for loop is never executed. If you insist on using a for loop (though perhaps a while loop would be better), change the conditional to be:

a < 1 || a > 2

My preference would be to use while instead of for:

while (a != 1 && a != 2)

Can a number be less than 1 and greater than 2 at the same time? No, right?

Then, check your condition, which says, a<1 && a>2 and now you know what is wrong with it.

Another problem that I see in your program is

a = scan.nextInt();
for (a=0;...)

What's the use of taking input from the user if you are resetting a to 0 ?

What you want to do is:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a;
        do {
            System.out.print("Write something here: ");
            a = scan.nextInt();
        } while (!(a == 1 || a == 2));

        // Display the correct input
        System.out.println("Finally, you have entered the correct value, which is " + a);
    }
}

A sample run:

Write something here: 3
Write something here: -7
Write something here: 4
Write something here: 0
Write something here: 2
Finally, you have entered the correct value, which is 2

For this type of loop i would suggest using "while" loop instead of "for" loop (you said you want to use while loop but actually used for loop).

"for" loops are used when you know in advance the number of times you want the loop to run. "while" loops are used when you don't know how many times the loop will run - which in your case depends on the input from the user.

Also, in your "for" loop you set the condition to be that "a" needs to be lower then 1 AND bigger then 2 (at the same time) which is impossible.

I suggest you switch to "while" loop:

while (a != 1 && a != 2)

but if you still want to use the "for" loop try changing the condition to be:

a < 1 || a > 2

Hope this helps, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM