四则运算java代码
时间: 2024-06-05 12:02:57 浏览: 69
四则运算是指加法、减法、乘法和除法这四种基本运算。以下是一个简单的Java代码示例,实现了四则运算:
```java
import java.util.Scanner;
public class ArithmeticOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个操作数:");
double num1 = scanner.nextDouble();
System.out.print("请输入第二个操作数:");
double num2 = scanner.nextDouble();
System.out.println("请选择运算符:");
System.out.println("1. 加法 (+)");
System.out.println("2. 减法 (-)");
System.out.println("3. 乘法 (*)");
System.out.println("4. 除法 (/)");
int operator = scanner.nextInt();
double result = 0;
switch (operator) {
case 1:
result = num1 + num2;
System.out.println("结果:" + result);
break;
case 2:
result = num1 - num2;
System.out.println("结果:" + result); break;
case 3:
result = num1 * num2;
System.out.println("结果:" + result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
System.out.println("结果:" + result);
} else {
System.out.println("除数不能为0!");
}
break;
default:
System.out.println("无效的运算符!");
break;
}
scanner.close();
}
}
```
阅读全文