File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Else without if compiler error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Else without if compiler error" Watch "Else without if compiler error" New topic
Author

Else without if compiler error

Matt Hall
Greenhorn

Joined: Feb 28, 2006
Posts: 24
The following switch statement gives me an 'else' without 'if' error, i do not understand this as there are if statements there. Can anybody help?

String j = Leader;
switch (j)
{
case 1:
if (Newcard > Highcard)
Highcard = Newcard;
Leader = 2;
else
break;
case 2:
if (Newcard > Highcard)
Highcard = Newcard;
Leader = 3;
else

break;
case 3:
if (Newcard > Highcard)
Highcard = Newcard;
Leader = 4;
else
break;
case 4:
if (Newcard > Highcard)
Highcard = Newcard;
Leader = 1;
else
break;
}



Thanks
Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
Withoutcurly braces after an if statement, only the next line is part of the if statement, which means the second line after is not part of the if and the else does not DIRECTLY follow the if
[ April 02, 2006: Message edited by: Rusty Shackleford ]

"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18977
    
  40

I am assuming that the "else" statements are for the previous "if" statements, as you stated that "there are if statements".

Instead of this...



Do you mean this...



What you mean is very important, as adding the brackets while will allow the code to compile, may not be what you actually want to do...

Henry
[ April 02, 2006: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Matt Hall
Greenhorn

Joined: Feb 28, 2006
Posts: 24
if (Newcard > Highcard) {
Highcard = Newcard;
Leader = 2;
} else
break;

This is correct, thanks for the help.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Else without if compiler error