我有这个代码...
import java.util.*;
public class SwitchExample {
public static void main(String[] args) {
System.out.print("Enter ID: ");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
System.out.print("Invalid. Enter again: ");
scanner.next();
}
int number = scanner.nextInt();
System.out.println("Your number was: " + number);
System.out.println("Test message got printed!");
}
}
键入有效输入是可以的,并且键入无效字符后,仍可以按要求运行。但是,在两种情况下键入Enter键都不会引发错误。请帮助我如何实现。我尝试了多种方法,但都没有奏效。
答案 0 :(得分:1)
好吧,您只是在扫描整数,然后尝试扫描“下一行”
while(scanner.hasNextLine())
如果您按Enter键,它将捕获,我想是。
答案 1 :(得分:1)
要输入,您需要添加一个特殊情况,诸如此类
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();
}