当用户在使用 Scanner 对象时输入整数时捕获异常
Catching an exception when a user inputs an integer while using a Scanner object
当用户在扫描仪中输入任何整数时,我试图捕获异常。我知道使用 String item = scan.nextLine() 将允许进行任何输入,包括整数。我创建了一个自定义异常来捕获数字 1。但是如果用户输入 999 或任何其他整数会发生什么。我怎样才能捕获那些其他整数作为异常的一部分?
进口java.util.Scanner;
导入 java.lang.Exception;
public class 示例一 {
public static void main(String[] args) throws TestCustomException {
System.out.println("Please enter any word:");
try {
Scanner scan = new Scanner(System.in);
String item = scan.nextLine();
if (item.contains("1")) {
throw new TestCustomException();
}
}catch (TestCustomException e) {
System.out.println("A problem occured: " + e);
}
System.out.println("Thank you for using my application.");
}
}
public class TestCustomException 扩展异常 {
TestCustomException (){
super("You can't enter any number value here");
}
}
正则表达式
public static void main(String[] args) {
System.out.println("Please enter any word:");
try {
Scanner scan = new Scanner(System.in);
String item = scan.nextLine();
Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
Matcher isNum = pattern.matcher(item);
if (isNum.matches()) {
throw new RuntimeException();
}
}catch (RuntimeException e) {
System.out.println("A problem occured: " + e);
}
System.out.println("Thank you for using my application.");
}
当用户在扫描仪中输入任何整数时,我试图捕获异常。我知道使用 String item = scan.nextLine() 将允许进行任何输入,包括整数。我创建了一个自定义异常来捕获数字 1。但是如果用户输入 999 或任何其他整数会发生什么。我怎样才能捕获那些其他整数作为异常的一部分?
进口java.util.Scanner; 导入 java.lang.Exception;
public class 示例一 {
public static void main(String[] args) throws TestCustomException {
System.out.println("Please enter any word:");
try {
Scanner scan = new Scanner(System.in);
String item = scan.nextLine();
if (item.contains("1")) {
throw new TestCustomException();
}
}catch (TestCustomException e) {
System.out.println("A problem occured: " + e);
}
System.out.println("Thank you for using my application.");
}
}
public class TestCustomException 扩展异常 {
TestCustomException (){
super("You can't enter any number value here");
}
}
正则表达式
public static void main(String[] args) {
System.out.println("Please enter any word:");
try {
Scanner scan = new Scanner(System.in);
String item = scan.nextLine();
Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
Matcher isNum = pattern.matcher(item);
if (isNum.matches()) {
throw new RuntimeException();
}
}catch (RuntimeException e) {
System.out.println("A problem occured: " + e);
}
System.out.println("Thank you for using my application.");
}