2 回答
TA贡献1780条经验 获得超3个赞
对于输入,您需要添加一个特殊情况,例如
String line = scanner.nextLine();
if (line .isEmpty()) {
System.out.println("Enter Key pressed");
}
这是您需要的完整源代码:
public static void main(String[] args) {
System.out.print("Enter ID: ");
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
else if (isInteger(readString)) {
System.out.println("Read integer");
}
else{
System.out.println("Read char");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
}
}
public static boolean isInteger(String s) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt()) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt();
return !sc.hasNext();
}
添加回答
举报