-1

My output is this:

% Enter a positive integer: 90

% 90

% Enter another positive integer:

90 is the first integer I type in, but it doesn't automatically go to "enter another positive integer", why is that? Thanks in advance!

Scanner sc = new Scanner (System.in);
int a, b, r, x,temp;

for (int i = 0; i<10; i++){
   System.out.print("Enter a positive integer: ");
      while (true){
           while (!sc.hasNextInt()){
           sc.next();
           System.out.print("Please enter a positive integer: ");
           }if (sc.nextInt()<0){
               System.out.print("Please enter a positive integer: ");
           }else{
               a = sc.nextInt();
               break;
           }
      }


  System.out.print("Enter another positive integer: ");
       while(true){
            if (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
            }else if(sc.nextInt()>0){
                b = sc.nextInt();
                break;
            } else{
                System.out.print("Please enter a positive integer: ");
            }

       }

2 Answers2

0

The problem is the code will enter the first two while loops, and then the user needs to enter a number (sc.next();).

Then assuming the number is greater than 0, you go into your else statement, and you then call a = sc.nextInt();; therefore the user has to type in something else there.

And the same applies to the second loop.

Seeing as you wish to use while loops, you could do something like:

boolean flag;
System.out.print("Enter a positive integer: ");
int num;
do {
    flag = true;
    num = sc.nextInt();
    if (num < 0) {
        flag = false;
        System.out.print("Please enter a positive integer: ");
    }
} while (!flag);

and put that in your loop.

Regarding your comment above (It's so that as long as my next token is not an int, it will keep prompting me to 'try again'), this is not true as if you enter a non-digit, the program will crash. You could use a try...catch to ensure the number is a digit. See here for an example.

achAmháin
  • 4,176
  • 4
  • 17
  • 40
0

Your first "90" entered in the System.in is consumed by the sc.nextInt() in the if statement. the second "90" entered is retrieved in the assignment statement a = sc.nextInt()

try changing to the following:

  while (true){
       while (!sc.hasNextInt()){
       sc.next();
       System.out.print("Please enter a positive integer: ");
       }
       a = sc.nextInt();
       if (a<0){
           System.out.print("Please enter a positive integer: ");
       }else{
           break;
       }
  }
Tan Wei Lian
  • 92
  • 1
  • 9