用Java写一个计算器代码
时间: 2023-11-23 21:08:06 浏览: 101
以下是使用Java编写的简单计算器代码:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result = 0.0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator");
break;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
}
}
使用此代码,用户将被要求输入两个数字和一个操作符。然后,程序将根据操作符执行相应的计算,并输出结果。
阅读全文