Have been struggling with this for a day, reading the discussion forum back and forth, no result. Anyone can tell me why the second call of the function aMenu() returns a zero and does not wait for new user input instead? I tried various things, like hasNextInt(), nextLine(), nothing worked. Shouldn't hasNextInt() block until the user writes something? How can I solve this? Thanks.
package FirstJavaPackage;
import java.util.Scanner;
public class testScanner
{
public static void main(String[] args)
{
int choice = aMenu();
System.out.println("You typed: "+choice);
choice = aMenu();
System.out.println("You typed: "+choice);
}
public static int aMenu()
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
Scanner keyboard = new Scanner(System.in);
if (keyboard.hasNextInt())
result = keyboard.nextInt();
keyboard.close();
return result;
}
}
The output is:
In aMenu... enter an int: 2 You typed: 2 In aMenu... enter an int: You typed: 0