Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Else without if compiler error

 
Matt Hall
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Henry Wong
author
Marshal
Pie
Posts: 20991
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Matt Hall
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if (Newcard > Highcard) {
Highcard = Newcard;
Leader = 2;
} else
break;

This is correct, thanks for the help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic