在Java中,你可以创建一个简单的四则运算程序来执行小学级别的加减乘除操作。以下是一个基本的示例:
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.println("请输入第二个数字:");
double num2 = scanner.nextDouble();
System.out.println("请选择运算符(+、-、*、/):");
char operator = scanner.next().charAt(0);
switch (operator) {
case '+':
System.out.println(num1 + " + " + num2 + " = " + add(num1, num2));
break;
case '-':
System.out.println(num1 + " - " + num2 + " = " + subtract(num1, num2));
break;
case '*':
System.out.println(num1 + " * " + num2 + " = " + multiply(num1, num2));
break;
case '/':
if (num2 != 0) {
System.out.println(num1 + " / " + num2 + " = " + divide(num1, num2));
} else {
System.out.println("错误!除数不能为零。");
}
break;
default:
System.out.println("错误!无效的运算符。");
}
scanner.close();
}
private static double add(double a, double b) {
return a + b;
}
private static double subtract(double a, double b) {
return a - b;
}
private static double multiply(double a, double b) {
return a * b;
}
private static double divide(double a, double b) {
return a / b;
}
}
这个程序首先从用户那里获取两个数字和一个运算符,然后根据运算符调用相应的函数(如add()
、subtract()
、multiply()
或divide()
)进行计算,并输出结果。
注意,在divide()
函数中添加了一个检查,以防止除以零的情况发生。