Mohamad-Ali Okasha
Mohamad-Ali Okasha

Reputation: 11

Java if statement not working as expected

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

Answers (3)

Md. Masudur Rahman
Md. Masudur Rahman

Reputation: 1078

  1. You have to remove semicolon (;) after the if (condition). If(condition) is not a statement and so semicolon should not be inserted.

  2. 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

Mark Zucchini
Mark Zucchini

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

Eran
Eran

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

Related Questions