public class Utils {
public static double add(double num1, double num2) {
return num1 + num2;
}
public static double substract(double num1, double num2) {
return num1 - num2;
}
public static double mulitply(double num1, double num2) {
return num1 * num2;
}
public static double division(double num1, double num2) {
if (num2 == 0) {
return -1;
}
return num1 / num2;
}
}
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) throws Exception {
double[] nums;
double num1;
double num2;
double result;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用于计算的两个数值,数值间用空格分隔");
System.out.println("请输入加数与被加数:");
nums = trans(scanner.nextLine());
num1 = nums[0];
num2 = nums[1];
result = Utils.add(num1, num2);
print("和为:", result);
System.out.println("请输入减数与被减数:");
nums = trans(scanner.nextLine());
num1 = nums[0];
num2 = nums[1];
result = Utils.substract(num1, num2);
print("差为:", result);
System.out.println("请输入乘数与被乘数:");
nums = trans(scanner.nextLine());
num1 = nums[0];
num2 = nums[1];
result = Utils.mulitply(num1, num2);
print("积为:", result);
System.out.println("请输入除数与被除数:");
nums = trans(scanner.nextLine());
num1 = nums[0];
num2 = nums[1];
result = Utils.division(num1, num2);
if (result == -1) {
System.out.println("分母不能为0");
} else {
print("商为:", result);
}
}
public static double[] trans(String input) throws Exception {
try {
String[] arr = input.split(" ");
return new double[]{Double.parseDouble(arr[0]), Double.parseDouble(arr[1])};
} catch (Exception e) {
throw new Exception("输入格式错误");
}
}
public static void print(String msg, double num) {
if (num == (int) num) {
System.out.println(msg + (int) num);
} else {
System.out.println(msg + num);
}
}
}
上面是代码,工程自己创建把代码复制进去就可以了。