-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.java
More file actions
70 lines (60 loc) · 2.51 KB
/
calculator.java
File metadata and controls
70 lines (60 loc) · 2.51 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.InputMismatchException;
import java.util.Scanner; // Correction 1: Changed 'until' to 'util'
public class Calculator {
public static void main(String[] args) { // Correction 2: Added opening brace for main method
// Step 1: Create a Scanner object for user input
Scanner scanner = new Scanner(System.in); // Correction 3: Used simple 'Scanner'
double num1 = 0;
double num2 = 0;
char operator = ' '; // Initialize operator
double result = 0.0;
try {
// Step 2: Get the first number
System.out.print("Enter the first number: ");
num1 = scanner.nextDouble();
// Step 3: Get the operator
System.out.print("Enter an operator (+, -, *, /): "); // Correction 4: Fixed 'oparator' typo and formatting
// Use next().charAt(0) to read the first character of the input
operator = scanner.next().charAt(0);
// Step 4: Get the second number
System.out.print("Enter the second number: ");
num2 = scanner.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid number.");
// Important: close scanner and exit gracefully
scanner.close();
return;
}
// Step 5: Perform the calculation using a switch statement
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero is not allowed.");
scanner.close();
return; // Exit the program on error
}
break;
default:
System.out.println("Error: Invalid operator entered.");
scanner.close();
return; // Exit the program on error
}
// Step 6: Display the result
System.out.println("\n--- Result ---");
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
System.out.println("--------------");
// Final Step: Close the scanner
scanner.close();
} // Correction 2: Added closing brace for main method
}