Hello all,
I'm relatively new to Java programming, I have a question about a piece of code from a video tutorial online:
static Scanner userInput = new Scanner(System.in); public static void main(String args[]){ System.out.print("Your favorite number: "); if(userInput.hasNextInt()){ int numberEntered = userInput.nextInt(); System.out.println("You entered " + numberEntered); }else{ System.out.println("Enter an integer next time."); } }
How is the if statement (userInput.hasNextInt()) "true" if it doesn't ask for user input before the if statement? The scanner asks for user input inside the if statement:
int numberEntered = userInput.nextInt();
It works for me, I just don't understand how. Thanks for any help in advance!!!