-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
70 lines (64 loc) · 2.47 KB
/
Copy pathCalculator.java
File metadata and controls
70 lines (64 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println("Available Operations: +, -, *, /, %, ^ (power), $ (square root)");
System.out.println("Note: For square root, only the first number is considered.");
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /, %, ^, $): ");
char operator = scanner.next().charAt(0);
double num2 = 0; // Initialize num2 as 0
if (operator != '$') {
System.out.print("Enter the second number: ");
num2 = scanner.nextDouble();
}
double result;
switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero!");
}
break;
case '%':
if (num2 != 0) {
result = num1 % num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero!");
}
break;
case '^':
result = Math.pow(num1, num2);
System.out.println("Result: " + result);
break;
case '$':
if (num1 >= 0) {
result = Math.sqrt(num1);
System.out.println("Result: " + result);
} else {
System.out.println("Error: Cannot calculate the square root of a negative number!");
}
break;
default:
System.out.println("Invalid operator!");
}
scanner.close();
}
}