好的,以下是一个使用 Java 实现的计算器代码:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.println("欢迎使用计算器");
System.out.println("请输入第一个数字:");
num1 = input.nextDouble();
System.out.println("请输入运算符(+ - * /):");
operator = input.next().charAt(0);
System.out.println("请输入第二个数字:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case '/':
if (num2 == 0) {
System.out.println("除数不能为零");
} else {
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
}
break;
default:
System.out.println("无效的运算符");
break;
}
input.close();
}
}
此代码简单地实现了加、减、乘以及除法运算,并提供了输入输出操作,支持用户交互。你可以根据需要进行修改、优化。
标签:Java,num1,num2,代码,System,result,计算器,println,out From: https://blog.51cto.com/u_16096459/6351433