Reputation: 11
I am trying to make a basic calculator for class.
I came up with the code below but all it does it addition.
Even if I use -
, *
, or /
.
Any tips?
Scanner input = new Scanner(System.in);
String num1, num2, operation, function;
System.out.println("Enter a simple equation: ");
function = input.nextLine();
int firstspace = function.indexOf(" ");
num1 = (function.substring(0,firstspace));
int lastspace = function.lastIndexOf(" ");
operation = (function.substring(firstspace,lastspace));
num2= (function.substring(lastspace+1,function.length()));
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals(" - "))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals(" / "))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals(" * "))
{
System.out.println("your answer is " + ( n1*n2));
}
}
}
Upvotes: 0
Views: 60
Reputation: 315
From what I see your code has this issue
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
Here you are putting a semi colon, which means when you run the code,it will execute this condition by default, so that means addition will always execute whether you like it or not.
So basically your code should be like this
if (operation.equals("+" ))
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals("-"))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals("/"))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals("*"))
{
System.out.println("your answer is " + ( n1*n2));
}
Hope this helps
Upvotes: 1