Reputation: 111
package mmm;
import java.util.Scanner;
public class Hi{
public static void main(String args[]){
int num1, num2, result, choice;
Scanner abhi = new Scanner(System.in);
System.out.println("You Have The Following Choices:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division ");
choice = abhi.nextInt();
System.out.println("Enter The First Number");
num1 = abhi.nextInt();
System.out.println("Enter The Second Number");
num2 = abhi.nextInt();
switch(choice){
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
default:
System.out.println("Error");
}
System.out.println("The Result Is "+result);
}
}
It says result
was not initialised; whereas I initialised it.
Where did I basically go wrong? I declared the variable type and all and did everything I could. I am a noob, so, pardon my silly questions and queries.
Any help would be appreciated!
Upvotes: 0
Views: 65
Reputation: 609
If you go in the default case of your switch, the result
variable will have received nothing when trying to print it.
You will have to give it a default value either before going in your switch, or inside your default
case.
Upvotes: 1
Reputation: 11251
Change you first line in the main method as following:
int num1, num2, result, choice = 0;
Upvotes: 0
Reputation: 8355
As pointed out by comments.
The variable result
is only gets value in cases choice
was 1
, 2
, 3
or 4
. So, not all code paths lead to the variable result
being assigned to a value.
However, all code paths lead to System.out.println("The Result Is "+result);
.
You either have to assign a value to result
in the default
case, or initialize it with a value at the when declaring it. . .
Upvotes: 1
Reputation: 44555
Local variables don't have a default value. You have to initialize the variables int num1, num2, result, choice;
with one, if you want to access them.
Upvotes: 1