I've been learning Java for about 3 weeks now, and I was hoping someone could check over my code for me, and let me know how to improve.
I am aware that the maths class could be removed (I could've typed answer = inputA * inputB
etc. within the switch statement) but this is just because I wanted to practice using multiple classes.
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();
}
}
And my second class...
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;
}
}
public static double sqrt(double a)
? see the API docs.oracle.com/javase/7/docs/api/java/lang/…. hint: good book, effective java, 2nd edition. Sometimes methods should be static. \$\endgroup\$