You will write a simple calculator program that asks the user to choose an opera
ID: 3787945 • Letter: Y
Question
You will write a simple calculator program that asks the user to choose an operation (+, -, *, /, %) and then asks for the 2 operands. It will calculate and store the results, and then display an appropriate message. • The only named variables you may use are pointer variables. (You will have to use the new operator to dynamically create the space for the values. • The program will repeat until the user decides to exit. You may implement this any way you wish. • You must use a switch statement for the options of the operator • You should have input validation, in case the user inputs a wrong kind of input
Explanation / Answer
For calculator, I am writing two classes,
Calculator.java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Maths Maths = new Maths();
double answer = 0;
double inputA, inputB;
char operator;
boolean done = false;
while (done == false) {
System.out.print("Please enter your sum: ");
inputA = input.nextDouble();
operator = input.next().charAt(0);
inputB = input.nextDouble();
switch (operator) {
case '+': answer = Maths.add(inputA, inputB);
break;
case '-': answer = Maths.subtract(inputA, inputB);
break;
case '*': answer = Maths.multiply(inputA, inputB);
break;
case '/': answer = Maths.divide(inputA, inputB);
break;
case '^': answer = Maths.power(inputA, inputB);
break;
}
System.out.println(answer);
}
input.close();
}
}
Maths.java
public class Maths {
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b) {
double answer = a*b;
return answer;
}
double divide(double a, double b) {
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
}
return answer;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.