Reputation: 11
I'm studying for a java programming exam, and I'm still a beginner. My problem in the if statement is:
int z;
if (z==1);
{//calculates area}
if (z==2)
{//calculates volume}
The goal is that if the user chooses 1 he'll find the area calculated and if he the user chooses 2 the volume will be calculated. However, in the output the area and volume are being calculated whatever the user chooses. Why is that?
Upvotes: 0
Views: 102
Reputation: 1078
You have to remove semicolon (;) after the if (condition). If(condition) is not a statement and so semicolon should not be inserted.
Double slash (//) has been used to comment out a line. That's why one of the brackets of if clause gets out of use.
The code should be looked like following:
int z;
if (z==1)
{
//calculates area
}
if (z==2)
{
//calculates volume
}
Upvotes: 1
Reputation: 925
Remove semicolon (;) from the end of first line.
Learn to format your code according specification
int z;
if (z==1) {
//calculates area
}
if (z==2) {
//calculates volume
}
Upvotes: 0
Reputation: 393771
You have to remove the ;
after the condition. Otherwise, the if statement is empty, and the code block following it is always executed.
if (z==1)
{//calculates area}
if (z==2)
{//calculates volume}
Or even better:
if (z==1) {
//calculates area
} else if (z==2) {
//calculates volume
}
since both conditions can't be true.
Upvotes: 5