程序会检查用户输入并确定它是肯定的还是否定的。 当用户提供无效的输入(非整数)(例如“ 444h”或“ ibi”)时,如何捕获错误。
我以为最终的else语句将捕获异常,但事实并非如此。
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = scan.nextInt();
scan.close();
if(num > 0)
{
System.out.println(num+" is positive");
}
else if(num < 0)
{
System.out.println(num+" is negative");
}
else if(num == 0)
{
System.out.println(num+" is neither positive nor negative");
}
else
{
System.out.println(num+" must be an integer");
}
}
}
我希望程序捕获异常并提示输入有效整数
答案 0 :(得分:3)
只需将代码包装在try..catch
block中即可。
完整代码:
import java.util.Scanner;
import java.util.InputMismatchException;
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
try {
int num = scan.nextInt();
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
} else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
} catch (InputMismatchException e) {
System.out.println("Error: Value Must be an integer");
}
scan.close();
}
}
祝你好运:)
答案 1 :(得分:1)
int num = 0;
try{
num =input.nextInt();
}catch(InputMismatchException ex) {
System.out.println("Enter Integer Value Only");
}
如果您从输入中获得非整数值,则必须在try块中编写int num = scan.nextInt();
该语句,然后InputMismatchException
就会出现,然后执行catch块。
答案 2 :(得分:1)
首先,如果您打算在应用程序运行期间再次使用扫描仪,请不要关闭扫描仪。关闭它后,您将需要重新启动应用程序才能再次使用它。
如上所述,您可以在Scanner#nextInt()方法上使用 try / catch :
0.2
或者您也可以使用Scanner#nextLine()方法代替它来接受字符串:
Scanner scan = new Scanner(System.in);
int num = 0;
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any number: ");
try {
num = scan.nextInt();
isValid = true;
}
catch (InputMismatchException ex) {
System.out.println("You must supply a integer value");
isValid = false;
scan.nextLine(); // Empty buffer
}
}
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
答案 3 :(得分:0)
使用正则表达式检查输入是否为数字
import java.util.regex.*;
Pattern.matches("[0-9]+", "123"); // this will return a boolean