-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.java
More file actions
48 lines (37 loc) · 1.27 KB
/
Copy pathcalculator.java
File metadata and controls
48 lines (37 loc) · 1.27 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
import java.util.Scanner;
public class calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
if (b == 0) {
System.out.println("Error: Cannot divide by zero");
return 0;
}
return (double) a / b;
}
public static void main(String[] args) {
calculator calc = new calculator();
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number: ");
int x = sc.nextInt();
System.out.println("Enter operator (+, -, *, /): ");
char op = sc.next().charAt(0);
System.out.println("Enter second number: ");
int y = sc.nextInt();
switch (op) {
case '+': System.out.println("Result: " + calc.add(x, y)); break;
case '-': System.out.println("Result: " + calc.subtract(x, y)); break;
case '*': System.out.println("Result: " + calc.multiply(x, y)); break;
case '/': System.out.println("Result: " + calc.divide(x, y)); break;
default: System.out.println("Invalid operator");
}
sc.close();
}
}