I used this code for an easy if/ else statement that will sum the answer if x was greater than y, and will subtract it if x was not greater than y ! For some reason I’m getting a run time error.
Can anyone help me with this?
The code is :
import java.util.Scanner;
public class calculation
{
public static void main(String[] args)
{
int x,y,answer;
Scanner kb = new Scanner(System.in);
System.out.println(" Enter x & Y " );
x = kb.nextInt();
y = kb.nextInt();
if (x > y) {
answer = (x + y);
}
else if (x < y) {
answer=(x-y);
}
}
}
This is the message I get : Warning: The local variable answer is never read
If the error you’re getting is something like this:
then the problem is that
answermight not have had any value set, and the computer gives up and prints an error message instead of possibly returning garbage.How can
answernot have a value set? You setanswertox+yifx>y, and ifx<yyou setanswer=x-y; but what ifx=y? There’s nothing that tells the computer what to do in that case. Even thoughxmight not be equal toyfor the particular inputs you typed into your program, Java gives you an error message now in the hopes that you would rather get an error now, when it can easily be fixed, than sometime much later when someone first inputs equal values ofxandy.You can fix this by changing
x>ytox>=y, orx<ytox<=y, or by adding a thirdx==ycase.If the warning you are getting is
Then you need to add a statement that uses
answerin some way, for example by adding this at the end of the method:However, note that this is just a warning, not an error, so even though the message pops up, it should run just fine—try it! Of course, you won’t be able to see what value
answergets, because, as the warning says,answeris never read in the current code.