How do you capture the enter key when using hasNextInt()? I have the following code and am trying to exit gracefully if the user just enters the return key. In the example below I was expecting to get back -9, but the program just hangs on the hasNextInt() line
import java.util.Scanner;
public class InputInt{
public static void main(String[] args){
InputInt x = new InputInt();
System.out.println(x.enterInt());
}
public int enterInt(){
int myInt = -9;
boolean isValid = false;
String lf = "";
Scanner kb = new Scanner(System.in);
while(!isValid){
System.out.print("please enter an integer: ");
if(kb.hasNextInt()){
myInt = kb.nextInt();
isValid = true;
}else{
lf = kb.nextLine();
if (lf.length() == 0)isValid = true;
}
}
return myInt;
}
}