java简单计算器代码大一
时间: 2025-01-07 10:11:10 浏览: 0
在Java中,编写一个简单的命令行计算器可以帮助大一学生理解基本的控制结构和数学运算操作。下面是一个基础版的示例,展示了如何创建一个可以执行加、减、乘、除的简单计算器:
```java
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2;
char operator;
System.out.println("请输入第一个数字:");
num1 = scanner.nextDouble();
System.out.println("请输入运算符 (+, -, *, /):");
operator = scanner.next().charAt(0);
switch (operator) {
case '+':
System.out.println("结果是:" + add(num1, scanner.nextDouble()));
break;
case '-':
System.out.println("结果是:" + subtract(num1, scanner.nextDouble()));
break;
case '*':
System.out.println("结果是:" + multiply(num1, scanner.nextDouble()));
break;
case '/':
if (scanner.nextDouble() != 0) // 防止除数为零
System.out.println("结果是:" + divide(num1, scanner.nextDouble()));
else
System.out.println("错误:除数不能为零!");
break;
default:
System.out.println("无效的运算符。");
break;
}
scanner.close();
}
// 加法方法
public static double add(double a, double b) {
return a + b;
}
// 减法方法
public static double subtract(double a, double b) {
return a - b;
}
// 乘法方法
public static double multiply(double a, double b) {
return a * b;
}
// 除法方法
public static double divide(double a, double b) {
return a / b;
}
}
阅读全文