-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
51 lines (38 loc) · 1.41 KB
/
Calculator.java
File metadata and controls
51 lines (38 loc) · 1.41 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
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
try {
System.out.println("Choose an operation. a = addition, s = subtraction, m = multiplication, d = division: \n");
char operation = number.next().charAt(0); // read first character of user input
System.out.println("Enter the first number: \n");
int num1 = number.nextInt();
System.out.println("Enter the second number: \n");
int num2 = number.nextInt();
switch (operation) {
case 'a':
System.out.println("The sum is: " + (num1 + num2));
break;
case 's':
System.out.println("The difference is: " + (num1 - num2));
break;
case 'm':
System.out.println("The product is: " + (num1 * num2));
break;
case 'd':
if (num2 != 0)
System.out.println("The quotient is: " + ((double)num1 / num2));
else
System.out.println("Error: Cannot perform division by zero.");
break;
default:
System.out.println("Invalid operation. Please enter a, s, m, or d.");
}
} catch (InputMismatchException e) {
System.out.println("Error: Please enter valid numbers only!");
}
// This tells Java: “I’m finished reading input — free up the resources. This is to prevent resource leaks”
number.close();
}
}