Write a program in java that mimics a calculator. The program will need to accep
ID: 3578978 • Letter: W
Question
Write a program in java that mimics a calculator. The program will need to accept as input two numeric double values, and accept the operation to be performed as the third input. The operation to be performed will be input in the form of the character representing the java operator for the operation to be performed (i.e + for addition, - for subtraction, * for multiplication, / for division, or % for modulus). Once the program has read these 3 inputs it will output the numbers, the operator, and the result. (For division, if the denominator is zero, the program will output an appropriate message (e.g. division by zero is an invalid operation). Some sample output may look as follows: 3 + 4 = 7 13 * 5 = 65 10 / 3 = 3.33333333
Explanation / Answer
package snippet;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
double a1,a2;
String op;
Scanner sc=new Scanner(System.in);
a1=sc.nextDouble();
op=sc.next();
a2=sc.nextDouble();
double re;
switch(op)
{
case "+":
re=a1+a2;
System.out.println(a1+"+"+a2+"="+re);
break;
case "-":
re=a1-a2;
System.out.println(a1+"-"+a2+"="+re);
break;
case "*":
re=a1*a2;
System.out.println(a1+"*"+a2+"="+re);
break;
case "/":
if(a2==0)
System.out.println("Division by zero is an invalid operation");
else
{
re=a1/a2;
System.out.println(a1+"/"+a2+"="+re);
}
break;
}
}
}
=======================================================================
Output:
2
+
3
2.0+3.0=5.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.