1 import java.util.Scanner; 2 3 public class JiSuanQi { 4 public static void execute(int first_number, int second_number) 5 throws MyException { 6 // 手写异常不能让输入的数为负数 7 if (first_number < 0 || second_number < 0) { 8 throw new MyException("参数不能为负数"); 9 } 10 } 11 12 public static void main(String[] args) { 13 for (;;) { 14 Scanner input = new Scanner(System.in); 15 System.out.println("请输入式子"); 16 String shizi = input.nextLine(); 17 String[] allfuhao = { "+", "-", "*", "/" }; 18 jiSuan(shizi, allfuhao); 19 20 } 21 } 22 23 private static void jiSuan(String shizi, String[] allfuhao) { 24 for (int i = 0; i < allfuhao.length; i++) { 25 for (int j = 0; j < shizi.length(); j++) { 26 String fu = String.valueOf(shizi.charAt(j)); 27 if (allfuhao[i].equals(fu)) { 28 try { 29 String first = shizi.substring(0, j); 30 Integer first_number = Integer.parseInt(first); 31 String second = shizi.substring(j + 1); 32 Integer second_number = Integer.parseInt(second); 33 execute(first_number, second_number); 34 if (i == 0) { 35 System.out.println(shizi + "=" 36 + (first_number + second_number)); 37 } else if (i == 1) { 38 System.out.println(shizi + "=" 39 + (first_number - second_number)); 40 } else if (i == 2) { 41 System.out.println(shizi + "=" 42 + (first_number * second_number)); 43 } else if (i == 3) { 44 45 System.out.println(shizi + "=" 46 + (first_number / second_number)); 47 } 48 49 } catch (MyException e) { 50 System.out.println("不允许使用负数"); 51 } catch (NumberFormatException e) { 52 System.out.println("不是数字"); 53 } catch (ArithmeticException e) { 54 System.out.println("除数不能为0"); 55 } 56 return; 57 } 58 59 } 60 61 } 62 System.out.println("没找到运算符号,重新输入"); 63 } 64 }
1 public class MyException extends Exception { 2 3 public MyException(){ 4 super(); 5 } 6 public MyException(String Exception ){ 7 super(Exception); 8 9 } 10 }