Tuesday, November 4, 2008

Published 11/04/2008 by with 0 comment

else without if

Programmers may see message “else without if” when the selection (if ... else if ... else) structure is used. This may happen for any of the following reasons:
Semicolon (;) is given after the last parenthesis of the condition
Error in use of the curly braces ( } ), may be the } is not closed before starting the next else if or the else or } is given more.

Here is an example of this error:
public class ElseWithoutIf
{
public static void main(String args[])
{
int a=10,b=5;
if(a==b);
{
System.out.println(a+" is not equal to "+b);
else
{
System.out.println(a+" is equal "+b);
}
}
}


Here we have given ; (semicolon) at the last of the first condition, it’s an error. Again, we haven’t closed the } of the if i.e., else is written within the ‘ if’. So we need to remove the ; and put another } before the else.

Now the correct code is:
public class ElseWithoutIfSolution
{
public static void main(String args[])
{
int a=10,b=5;
if(a==b)
{
System.out.println(a+" is not equal to "+b);
}
else
{
System.out.println(a+" is equal "+b);
}
}
}
    email this       edit

0 comments:

Post a Comment