I am working on a VERY simple calculator with Java and it does not seem to output an answer after selecting the operation. The code is as follows:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
Double fnum;
Double snum;
Double answer;
String operation;
System.out.println("Enter a number.");
fnum = keyboard.nextDouble();
System.out.println("Enter another number.");
snum = keyboard.nextDouble();
System.out.println("What operation do you wish for? [Multiplication, Addition, Subtraction, Division]");
operation = keyboard.next();
if (operation == "Multiplication" || operation == "multiplication" || operation == "*") {
answer = fnum * snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Division" || operation == "division" || operation == "/") {
answer = fnum / snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Addition" || operation == "addition" || operation == "+" || operation == "add") {
answer = fnum + snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Subtraction" || operation == "subraction" || operation == "-" || operation == "subtract"){
answer = fnum - snum;
System.out.print("Your answer is: " + answer);
}
else {
System.out.println("This is not valid.");
}
}
}
and this is the output:
Enter a number.
6
Enter another number.
6
What operation do you wish for? [Multiplication, Addition, Subtraction, Division]
Multiplication
This is not valid.
Any help would be very appreciated. P.S. there are no errors. Thanks!
There are 2 problems. A problem with Scanner and with the condition
keyboard.nextDouble(), keyboard.next() etc... (all except .nextLine() ) leave the newline ( \n or Enter ) in the buffer. This can cause problems etc..
I suggest adding a delimiter using keyboard.useDelimiter("\n");. This only needs to be done once and can be done right after initialization of keyboard.
That way, it will only see the Enter as a signal to end that current input.
Also, the conditions must all be using the .equals() method or .equalsIgnoreCase() which is written as:
operation.equals("Multiplication");
or
operation.equalsIgnoreCase("multiplication");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With