• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java if-else  RSS feed

 
Jay Mize
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So the program test to see if the user input is a positive number and an integer. The "if" statement test if it an integer, the "else if" test if it negative. If it a negative or a decimals, the user is ask to input a positive integer. The problems is at the else statement, it is awaiting for the user input again, I want it to use the value from "System.out.print("Enter the test number: ");" if it pass the if and else if test. Thanks
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you call hasNextInt() or nextInt() on the Scanner object (as you are doing in lines 13, 17 and 24), the program will wait for the user to enter something.

If you want to print something before the program waits for the user to input the number, then put a System.out.print(...) statement before the line where it's going to wait.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I never use Scanner, because I find it unwieldy, so I might be missing something, but I think that...

Once the user has entered something, if the !hasNextInt() test is true--that is, if they enter a non-int--it doesn't look like you're consuming that token. Calling hasNextInt() just peeks at the next token; it doesn't consume it, so if they entered "ZZZ", you can call hasNextInt() 100 time in a row and it will just keep looking at that "ZZZ" and saying, "Nope, the next token is not an int." You need to call next() to advance past it.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you should create just one Scanner, outside your loop, rather than creating a new on on each iteration as you're doing now.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!