Reputation: 15
error showing in the last line as
:::: variable result might not have been initialized
this is my code:
public static void main(String args[]){
int n1, n2, result;
char oper;
n1=1000;
n2=200;
oper= '+';
if(oper == '+')
result=n1+n2;
else if(oper == '-')
result= n1-n2;
else if(oper == '*')
result= n1*n2;
else if(oper == '/')
result= n1/n2;
else if(oper == '%')
result= n1%n2;
System.out.println("Answer: "+result);
}
Upvotes: 1
Views: 714
Reputation: 3817
Your first line should be:
int n1, n2, result=0;
result
variable was not initialized nor it could be calculated from the code, hence the compiler thinks it won't find the value of the variable. Thus its giving compilation error.
Upvotes: 1
Reputation: 13964
You need to understand why you got this error:
In case of method's local variable, Java guarantees that the variable is properly initialized before it's used.
Variable result
may miss getting initialized in case none of the if-else if
clause gets satisfied. Note that you have not put any else
clause at end to update variable result
before it get used in this statement System.out.println("Answer: "+result);
Upvotes: 1