2

I have a while loop that isn't executing. I don't believe there is an infinite loop or priming problem, but is there? I can't find my logical error!

public class Test
{
    public static void main (String [] args)
    {
        int i = 1;
        int j = 1;
        while  ((i < 10) && (j*j != 25));
        { 
           i++;  
           ++j;
           System.out.println( i * j );
        }   
    }
}

1 Answer 1

15

Remove the semicolon after the while loop

public static void main (String [] args)
{
     int i = 1;
     int j = 1;
     while  ((i < 10) && (j*j != 25)) //Semicolon removed from here
     { 
        i++;  
        ++j;
        System.out.println( i * j );
     }   
}

Any statement that directly comes after the loop declaration is considered the whole block if it's not enclosed with braces.

I.E

if( true ) 
    System.out.println( "hello" );
    System.out.println( "world" );

Is treated as

if( true ) {
     System.out.println( "hello" );
}
System.out.println( "world" );

A single semicolon is considered as empty statement and thus made up your whole loop body.

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

2 Comments

Almost a +1. It needs an explanation of why this fixes the problem.
he also had an infinite loop, even though he was not thinking so

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.