當用戶在掃描儀中輸入任何整數時,我試圖捕獲例外。我知道使用 String item = scan.nextLine() 將允許進行任何輸入,包括整數。我創建了一個自定義例外來捕獲數字 1。但是如果用戶輸入 999 或任何其他整數會發生什么。我怎樣才能將那些其他整數作為例外的一部分?
匯入 java.util.Scanner; 匯入 java.lang.Exception;
公共類 ExampleOne {
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.");
}
}
公共類 TestCustomException 擴展例外 {
TestCustomException (){
super("You can't enter any number value here");
}
}
uj5u.com熱心網友回復:
正則運算式
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.");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355024.html
上一篇:在Swift中以編程方式訪問和更新stackview中的label.text或其他UILabel屬性
下一篇:拯救父方法在子行程中引發的例外
