0

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1
  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
}

Comments

0

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
}

1 Comment

Nitpicking when talking about code conventions: There should be a blank line between local var declaration and first statement. And there should be spaces around the ==. Java Code Conventions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.