views:

79

answers:

2

Hi! I'm new to this so please excuse my presumably simple questions. Hope you'll be able to help me out quite easily! I'm making an app that uses 4 variables to calculate the amount of water recommended for the user. The problem with this switch statement is that no matter what value i set age to, it always does the last case. Why is this?

Also, since my variables are all obtained from different (IBAction) methods, do they need to be defined as global variables? And how would i go about doing so?

PLEASE HELP!

Thanks so much :)

-(IBAction) updatePrefs:(id) sender
{

    switch (age){
     case 1:
         RWI = 1;
         Output.text = [NSString stringWithFormat:@"You should drink 1 litre a day"];
     case 2: 
         Output.text = [NSString stringWithFormat:@"You should drink 1.5 litres a day"];
     case 3:
         RWI = (weightkg * weightpounds * activity);
         Output.text = [NSString stringWithFormat:@"You should drink 2 litres a day"];
         break;
     default:   
         break;
}
A: 

Put a

break;

At the end of each case block of statements. Without the break; your code path of execution simply falls through each case set of statements and you end up with you var being assigned the last value in the switch statement.

TomH
ahhhh! :D cool thanks guys!
anneke
If you like the answer, please accept it.
TomH
A: 

I've missed some break stament you have to insert break after every case stament.

You're code should look like:

switch (age){

    case 1: RWI = 1; 
        Output.text = [NSString stringWithFormat:@"You should drink 1 litre a day"]; 
        break;
    case 2: 
        Output.text = [NSString stringWithFormat:@"You should drink 1.5 litres a day"]; 
        break;
    case 3: RWI = (weightkg * weightpounds * activity); 
        Output.text = [NSString stringWithFormat:@"You should drink 2 litres a day"]; 
        break; 
    default:
    break; 
}
Luca Bernardi