我有这个代码...
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!");
}
}
键入有效的输入是可以的,并且在键入无效字符后,它仍然可以按要求工作。但是,键入回车键时,无论哪种情况都不会引发错误。请帮助我如何实现这一目标。我尝试了多种方法,但没有一种奏效。
好吧,您只是在扫描整数尝试扫描"下一行"
while(scanner.hasNextLine())
如果你按回车键,那会抓住,我假设是这样。
对于 enter,您需要添加一个特殊情况,如下所示
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();
}