Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   switch statement (http://www.programmingforums.org/showthread.php?t=11812)

NightShade01 Nov 5th, 2006 7:40 PM

switch statement
 
just a quick question about switch statements. is it true that you always have to use break; at the end of each case in a switch statement? Someone was trying to explain a way to me where you don't but every text book i've read says you must.

DaWei Nov 5th, 2006 7:42 PM

Only if you don't want to execute the next case. That's most of the time.

xavier Nov 5th, 2006 11:23 PM

And a short example :
:

int n ;

switch(n){
  case 0:
  case 1:
  case 2: System.out.println ( "the number is <= 2"); break;
  case 3:
  case 4:
  case 5: System.out.println ( "the number is >=3 and <= 5"); break;
  default :  System.out.println ( "the number is grater than 5"); break;
}


crawforddavid2006 Nov 5th, 2006 11:31 PM

just to let you know xavier... that won't do anything since n is not defined :p

now if you did something like this
:

int n = 0;
while(n < 3)
{
switch(n)
{
    case 0: System.out.println("0"); break;
    case 1: System.out.println("1"); break;
    case 2: System.out.println("2"); break;
}
n++;
}


it would work

xavier Nov 6th, 2006 1:39 AM

Quote:

Originally Posted by crawforddavid2006 (Post 118457)
just to let you know xavier... that won't do anything since n is not defined :p

Yeah, you'r right, but the focus was the switch statement. I guess he cuold try the code a few times and initialize n to different values. I'm sure he would have realized that :p

Mixmaster Jan 11th, 2007 2:40 AM

I thought you had to use break all the time as well. Im glad you asked that


All times are GMT -5. The time now is 8:09 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC