0

I want that java check if the enter value is positive and repeat the request until is not true but I don't want that inside a while condition statement ( in brackets )
```

 System.out.println("Enter positive value");
                Scanner scanner = new Scanner(System.in);
                scanner.nextInt();
               while (  scanner.nextInt() <= 0) {//I what to request scanner in that section
               System.out.println("Enter positive value");
    }```

    but if I write it like this 

  ```  

while (  scanner.nextInt() <= 0) {
                  scanner.nextInt()//it will ask the input 2 times to enter the value , so how i can prevent the executing in the  scanner.nextInt() <= 0 in brackets
               System.out.println("Enter positive value");
        }
        
peterooon
  • 23
  • 5
  • I don't understand the question. If you don't want `nextInt` running inside your while loop then... don't put it in the while loop. You're the one who wrote the code. – Silvio Mayolo Jul 03 '21 at 17:01
  • i mean that i dont want that it run inside the bracket here while ( scanner.nextInt() <= 0) and as i understood it can be solve by assigning scanner.nextInt to an variable – peterooon Jul 03 '21 at 17:28

2 Answers2

0

This question could use some clarification, but if I'm understanding correctly what you're looking for can be solved with the following:

int input = -1;
while (input <= 0) {
System.out.println("Enter positive value");
input = scanner.nextInt();
}

This will cause the while loop to be forced to run, and then the input can be set by the user from within it.

Also, just a bit of Java advice, I suggest using Integer.parseInt(scanner.nextLine()) instead of scanner.nextInt(). It will save you lots of headaches in the future.

CobaltGecko
  • 188
  • 9
0

This can be a good fit for do..while:

int i = -1;
do {
  System.out.println("Enter positive value");
  i = scanner.nextInt();
} while ( i <= 0 )
Gaël J
  • 11,274
  • 4
  • 17
  • 32