snksnk
snksnk

Reputation: 1595

if statement gone wrong -xcode

Guys what am I doing wrong?

if (numberstring.intValue <=15) {
    rankLabel.text = @"A1";
}
else if (numberstring.intValue >16 && <=40){       
    rankLabel.text = @"A2";
}

I get an error on the "<=40" ..

Upvotes: 1

Views: 146

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

You missed off a variable reference:

if (numberstring.intValue <=15) {
    rankLabel.text = @"A1";
}                                  //        vv here vv
else if (numberstring.intValue >16 && numberstring.intValue <= 40){       
    rankLabel.text = @"A2";
}

As an optional extra, it looks like numberstring is an NSString object, which you are repeatedly converting to an integer in order to test various ranges. That operation is quite expensive, so you are better off doing the conversion once:

int value = [numberstring intValue];
if (value <=15) {
    rankLabel.text = @"A1";
}
else if (value >16 && value <= 40){       
    rankLabel.text = @"A2";
}

Also note that the intValue method is not a property so I would avoid using the Objective-C 2.0 dot syntax to access it and use the normal method calling mechanism.

Upvotes: 5

Hosam Aly
Hosam Aly

Reputation: 42443

The && operator links two clauses together. However, each clause is independent, so each one has to be syntactically correct on its own if the other was removed. If you apply this rule to your condition, you can see that "<=40" is not syntactically correct on its own. Thus you need to reference the value being compared, as follows:

if (numberstring.intValue > 16 &&
    numberstring.intValue <= 40)    // this is syntactically correct on its own

Upvotes: 2

Related Questions