3
votes

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.

2
put Scanner inside while loop,Abdelrahman Gobarah

2 Answers

0
votes

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.");
0
votes

I believe this is what you're trying to achieve.

    int i = 0; // int is 0

    while (i <= 0) {
        // int is 0 or a negative number
        System.out.println("#1\n Input Validation\n Positive values only");
        System.out.print(" Please enter a value: ");
        Scanner scan = new Scanner(System.in);
        i = scan.nextInt();

        if (i > 0) {
            System.out.println("The value is: " + i);
        } else {
            System.out.println("Sorry. Only positive values.");
        }
        // if number is positive then continue to termination. If negative then repeat loop
    }

Pay closer attention to where you place your while loop as your initial placement would certainly result in an infinite loop

while (i > 0)
{
    System.out.println("The value is: " +i);
    // number is positive - repeat loop containing only this line of code to infinity
}
// number is either 0 or negative so continue to termination