-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
72 lines (58 loc) · 2.38 KB
/
Calculator.java
File metadata and controls
72 lines (58 loc) · 2.38 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
71
72
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //scanner
System.out.print("Please input the first number: "); // recieve numbers
double firstnum = scanner.nextDouble();
System.out.print("Please input the second number: ");
double secondnum = scanner.nextDouble();
System.out.println("Second number = " + secondnum);
boolean validprompt = false; // recieve operation
String operation = "DEBUG";
while (!validprompt) {
System.out.print("Please input the operation (+,-,*,/) ");
String i = scanner.next();
switch (i) {
case "+":
operation = "+";
validprompt=true;
System.out.println("You chose" + operation);
break;
case "-":
operation = "-";
validprompt=true;
System.out.println("You chose " + operation);
break;
case "*":
operation = "*";
validprompt=true;
System.out.println("You chose " + operation);
break;
case "/":
operation = "/";
validprompt=true;
System.out.println("You chose " + operation);
if (secondnum == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
break;
default:
System.out.println("Try again.");
break;
}
}
scanner.close();
System.out.println(firstnum + " " + operation + " " + secondnum + " = " + calculate(firstnum, secondnum, operation));
}
public static double calculate(double num1, double num2, String operator) {
switch (operator) {
case "+": return num1+num2;
case "-": return num1-num2;
case "*": return num1*num2;
case "/": return num1/num2;
default:
System.exit(1);
return -1;
}
}
}