当您键入字母而不是数字时程序崩溃,如何保护此程序?


public static void main(String args[]) { /* problem*/
Scanner scan=new Scanner (System.in);       
int a; // problem//
System.out.println("a nedir");
a=scan.nextInt();
}

据我了解,当输入不是整数时,程序会停止。所以这里有一个简单的解决方案:使用方法nextLine((而不是nextInt((。检查输入是否不是数字捕获异常并继续,除非得到数字。

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int number = 0;
while (true) {
try {
number = Integer.parseInt(input);
return;
} catch (Exception e) {
System.out.println("Invalid number");
}
input = scanner.nextLine();
}

Scanner.nextInt(( 如果未找到整数,则会引发异常。您要么需要捕获异常并处理它,要么使用 Scanner.hasNextInt(( 阻止它发生

例如:

public static void main(String args[]) {
Scanner scan = new Scanner(System.in);       
int a;
System.out.println("a nedir");
if(scan.hasNextInt()){
a = scan.nextInt();
}
else{
//Add code to handle invalid input here
//ie. propmt the user to renter input or something like that
}
}

如果将 else 块留空,它仍然有效,但当您输入非数字输入时不会发生任何事情。

最新更新