# If/Else Statment Help

• January 17th, 2012, 03:02 PM
aandcmedia
If/Else Statment Help
I have a simple If/Else program that wont seem to work correctly! Can anyone spot the error?

package lab1;
import javax.swing.JOptionPane;

public class Exercise_5 {
public static void main(String[] args) {
String number1 = JOptionPane.showInputDialog("Enter One Number: ");
String number2 = JOptionPane.showInputDialog("Enter Another Number: ");
String operation = JOptionPane.showInputDialog("Enter an Operation, Type 1 for Addition, Type 2 for Subtraciton, Type 3 for Multiplication, Type 4 for Divison: ");

int number1i = Integer.parseInt(number1);
int number2i = Integer.parseInt(number2);
int operationi = Integer.parseInt(operation);

int add = number1i + number2i;
int sub = number1i - number2i;
int multi = number1i * number2i;
int divi = number1i / number2i;

if (number2i == 0){
String num = "Congrat's! you broke the universe and divided by 0";
}
else {
if (operationi == 1) {
int number = sub;
String num = Integer.toString(number);
} else if (operationi == 2) {
String num = Integer.toString(number);
} else if (operationi == 3) {
int number = multi;
String num = Integer.toString(number);
} else if (operationi == 4) {
int number = divi;
String num = Integer.toString(number);
}
else {
String num = "Sorry you did not enter a correct operating value";
}
}

String output = "After calculating the two numbers, the answer is: "+ num;
JOptionPane.showMessageDialog(null, output);

}
}
• January 17th, 2012, 03:10 PM
newbie
Re: If/Else Statment Help
For future reference, please surround your code in tags as found in my signature.
the answer is: "+ num;, the compiler can't find the variable num, because it doesn't exist in the scope it is used.
By declaring variables inside if statements, it's scope is local to that conditional block.

You should declare and initialise the variable num outside of the if blocks, and alter them inside.