使用Java的基本计算器程序
创建一个简单的计算器,它可以根据用户输入执行基本的算术运算,如加法、减法、乘法或除法。
例子 :
Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0
使用的方法:
- 使用 Scanner 类获取两个数字。 switch case 分支用于执行特定部分。
- 使用 switch case 来评估各自的操作。
Java
// Java program for simple calculator
import java.io.*;
import java.lang.*;
import java.lang.Math;
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args)
{
// stores two numbers
double num1, num2;
// Take input from the user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers");
// take the inputs
num1 = sc.nextDouble();
num2 = sc.nextDouble();
System.out.println("Enter the operator (+,-,*,/)");
char op = sc.next().charAt(0);
double o = 0;
switch (op) {
// case to add two numbers
case '+':
o = num1 + num2;
break;
// case to subtract two numbers
case '-':
o = num1 - num2;
break;
// case to multiply two numbers
case '*':
o = num1 * num2;
break;
// case to divide two numbers
case '/':
o = num1 / num2;
break;
default:
System.out.println("You enter wrong input");
break;
}
System.out.println("The final result:");
System.out.println();
// print the final result
System.out.println(num1 + " " + op + " " + num2
+ " = " + o);
}
}
输出:
Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0
时间复杂度: O(1)
辅助空间: O(1)