'while' infinite loop using scanner input and pos/neg numbers

simonshampoo :

I can't seem to understand how to use a while loop to determine whether a number is positive or not. While (I > 0), if I put any positive number, it will always result above 0 meaning there's an infinite loop.

int i = 0;

System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation
System.out.print(" Please enter a value: ");

Scanner scan = new Scanner(System.in);
i = scan.nextInt();

while (i > 0)
{
    System.out.println("The value is: " +i);
} 

System.out.println("Sorry. Only positive values.");

Also, when I input a negative number, it doesn't go back to the scanner to possibly input a positive number.

Anuradha :

You can go to this kind of approach:

    int i = 0;

    System.out.println("#1\n Input Validation\n Positive values only"); // #1 Input Validation

    Scanner scan = new Scanner(System.in);

    while (i >= 0) {
        System.out.print(" Please enter a value: ");
        i = scan.nextInt();
        if (i > 0) {
            System.out.println("The value is: " + i);
        } else {
            break;
        }
    }

    System.out.println("Sorry. Only positive values.");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415455&siteId=1