运行结果:
br:javacode br$ javac NumberFormatException.java
br:javacode br$ java NumberFormatException 45 34
Please use java NumberFormatException operand1 operator operand2
java NumberFormatException 45x + 34
Wrong input 45x
java NumberFormatException 45 1 33
Wrong input: 1
java NumberFormatException 45 / 3
45 / 3 = 15.0
NumberFormatException.java (不使用异常处理)
class NumberFormatException {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Please use java NumberFormatException operand1 operator operand2");
System.exit(1);
}
if (isDigital(args[0])) {
if (args[1].length() == 1) {
if (args[1].charAt(0) == '+' || args[1].charAt(0) == '-'
|| args[1].charAt(0) == '*' || args[1].charAt(0) == '/') {
if (isDigital(args[2])) {
char operator = args[1].charAt(0);
double result = 0;
switch (operator) {
case '+':
result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
break;
case '-':
result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
break;
case '*':
result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
break;
case '/':
result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
break;
}
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
System.exit(0);
}
} else
System.out.println("Wrong input: " + args[1]);
} else
System.out.println("Wrong input: " + args[1]);
}
System.exit(1);
}
public static boolean isDigital(String args) {
for (int i = 0; i < args.length(); i++)
if (!Character.isDigit(args.charAt(i))) {
System.out.println("Wrong input " + args);
return false;
}
return true;
}
}
NumberFormatException1.java (使用异常处理)
class NumberFormatException1 {
public static void main(String[] args) {
try {
if (args.length != 3)
throw new IllegalArgumentException ("Please use java NumberFormatExceptionX operand1 operator operand2");
if (isDigital(args[0])) {
if (args[1].length() == 1) {
if (args[1].charAt(0) == '+' || args[1].charAt(0) == '-'
|| args[1].charAt(0) == '*' || args[1].charAt(0) == '/') {
if (isDigital(args[2])) {
char operator = args[1].charAt(0);
double result = 0;
switch (operator) {
case '+':
result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
break;
case '-':
result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
break;
case '*':
result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
break;
case '/':
result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
break;
}
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
}
}
}
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
}
public static boolean isDigital(String args) {
for (int i = 0; i < args.length(); i++)
if (!Character.isDigit(args.charAt(i)))
return false;
return true;
}
}