-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathCalculator.java
43 lines (40 loc) · 1.48 KB
/
Calculator.java
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
/*
Write a Java program to implement a simple calculator. The program should prompt the user to enter two numbers and an
operator (+, -, *, or /) and then perform the corresponding operation and display the result.
For example, if the user enters 4, 5, and +, the program should display 9 as the result. Similarly, if the user enters 10, 3,
and *, the program should display 30 as the result.
Your program should handle invalid inputs gracefully, for example, if the user enters an operator that is not one of the four
allowed operators or if the user enters non-numeric inputs.
*/
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 1st number: ");
int a = sc.nextInt();sc.nextLine();
System.out.print("Enter 2nd number: ");
int b = sc.nextInt();sc.nextLine();
System.out.print("Enter operator: ");
char op = sc.nextLine().charAt(0);
if(op == '+')
{
System.out.println(a+" "+op+" "+b+" = "+(a+b));
}
else if(op == '-')
{
System.out.println(a+" "+op+" "+b+" = "+(a-b));
}
else if(op == '*')
{
System.out.println(a+" "+op+" "+b+" = "+(a*b));
}
else if(op == '/')
{
System.out.println(a+" "+op+" "+b+" = "+(a/b));
}
else
{
System.out.println("Invalid operator");
}
}
}