Program Specication: Write a Java program that emulates a simple calculator: Pro
ID: 3551950 • Letter: P
Question
Program Specication:
Write a Java program that emulates a simple calculator:
Prompts the user to input the left operand and read it into a double variable.
Prompts the user to input the right operand and read it into a double variable.
Display a menu which gives the user the choice of the following menu options:
1 -> Multiplication
2 -> Division
3 -> Addition
4 -> Subtraction
and uses a user validation loop to read their response into a String variable.
Note: You must repeatedly get the users response until it is exactly one of the characters 1 2 3 4
Compute the result of the arithmetic expression, based on the operands and operator provided, and
display the entire expression with its result.
Grading:
Performance Indicator [1] [2] [3]
Readability and documentation 1 2 2
Use of loop(s) operators 1 2 2
Functional requirements 2 3 4
Eciency 1 2 2
Sample run(s):
---------------------------------------------
Enter the left operand : 1.2
Enter the right operand : 3.4
---------------------------------------------
1 -> Multiplication
2 -> Division
3 -> Addition
4 -> Subtraction--------------------------------------------
Choose an operator from the above menu : p
Choose an operator from the above menu : 7
Choose an operator from the above menu : 1
---------------------------------------------
1.2 * 3.4 = 4.08
---------------------------------------------
Explanation / Answer
import java.util.Scanner;
public class Calculator{
public static void main(String []args){
Scanner ss = new Scanner(System.in);
String op[] = {"*","/","+","-"};
System.out.println("Enter the left operand");
double l = ss.nextDouble();
System.out.println("Enter the right operand");
double r = ss.nextDouble();
System.out.println("1 -> Multiplication 2 -> Division 3 -> Addition 4 -> Subtraction");
System.out.print("Choose an operator from the above menu :");
int re = ss.nextInt();
while(re<1 || re>4){
System.out.print("Choose an operator from the above menu :");
re = ss.nextInt();
}
double res=0.0;
if(re==1) res = l*r;
else if(re==2){
res = l/r;
}
else if(re==3) res = l+r;
else if(re==4) res = l-r;
System.out.println(l+""+op[re-1]+""+r+" = "+(res));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.