简易计算器Java代码
时间: 2024-10-20 21:01:51 浏览: 32
简易计算器java代码
在Java中编写一个简易计算器的代码,通常会涉及到用户输入两个数字和选择运算符,然后执行相应的计算。下面是一个简单的控制台版计算器的例子:
```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("请输入操作符(+, -, *, /):");
String operator = scanner.next();
double num2;
switch (operator) {
case "+":
num2 = scanner.nextDouble();
double result = add(num1, num2);
System.out.println("结果: " + result);
break;
case "-":
num2 = scanner.nextDouble();
result = subtract(num1, num2);
System.out.println("结果: " + result);
break;
case "*":
num2 = scanner.nextDouble();
result = multiply(num1, num2);
System.out.println("结果: " + result);
break;
case "/":
if (num2 != 0) { // 防止除数为零
num2 = scanner.nextDouble();
result = divide(num1, num2);
System.out.println("结果: " + result);
} else {
System.out.println("错误: 除数不能为零!");
}
break;
default:
System.out.println("错误: 无效的操作符!");
break;
}
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;
}
}
```
这个程序首先获取用户的输入,然后根据用户指定的运算符调用相应的函数进行计算。记得关闭`Scanner`以释放资源。
阅读全文