# [Question]Simple Calculator problem?

• 02-01-2011, 09:57 PM
AlleDingeAndern
[Question]Simple Calculator problem?
I'm an amateur Java programmer.
Started learning, but then had some issues, and proceeded to learn Flash. Flash isn't exactly what I'm looking for, so I'm trying Java again. I have a problem with a calculator I'm attempting to make.
I was wondering if you could help me point out the flaw(s) in my calculator... THe source code is as follows, and it's pretty basic. I just can't get it to display the final output number...

import java.util.Scanner;

public class SimpleCalculator {

public static void main(String[] args) {
// TODO: Input/Output integers - only 1 scanner variable needed

System.out.println("Please enter a number below, can be decimal or whole");
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
double num1 = scan.nextDouble();

System.out.println("Number one equals "+ num1);
System.out.println("Please enter a second number below");

double num2 = scan.nextDouble();
System.out.println("Number two equals "+ num2);

System.out.println("Please enter an operator for these numbers: +,-,*,/");
String oper = scan2.nextLine();

System.out.println("Your chosen operator is " + oper);

if (oper == "/")
{double num3 = num1/num2;}
else if (oper == "+")
{double num3 = num1+num2;}
else if (oper == "-")
{double num3 =num1 - num2;}
else if (oper == "*")
{double num3 = num1*num2;}

System.out.println("The finalized output for your numbers are: " + num3);
}
}
It always says, in the last line, num3 cannot be resolved to a variable.

I just can't seem to get this to work, I've tried setting double num3 = 0; then running the code, I've also tried removing it completely...

Any help would be gladly appreciated, thanks, Joe.
• 02-01-2011, 10:11 PM
mastal

Also check how to compare Strings in Java.
• 02-01-2011, 10:13 PM
ace84
Hey,

instead of testing a value with the '=' sign, use the .equals comparison instead. Also declare 'num3' before the if statement.

For example:
double num3 = 0;

if( oper.equals("-" ) )
num3 = num1 - num2;
else if( oper.equals("*" ) )
num3 = num1 * num2;
else if( oper.equals("/" ) )
num3 = num1 / num2;
else
num3 = num1 + num2;

that should give you the correct results.
• 02-01-2011, 10:21 PM
AlleDingeAndern
@Mastal
Will do, Thanks!

@Ace84
That worked! Thanks! Two hours trying to fix this, solved in a matter of minutes. Thanks again!
~Joe
• 02-02-2011, 03:19 AM
sunde887
If you don't understand/didn't find the explanation of what caused your problem here is a quick one:

The double num3 is declared inside of curly braces, and thus it has a scope of only inside the curly braces, once the braces are exited, the declared variable no long exists.