Objective C if statement not working
I have been trying to find out the problem to this for a day now, and can't seem to find the fix.
int person;
-(IBAction)personOne:(id)sender{
[twoPerson stopAnimating];
[fourPerson stopAnimating];
[threePerson stopAnimating];
[onePerson startAnimating];
person = 1;
}
-(IBAction)personTwo:(id)sender{
[threePerson stopAnimating];
[fourPerson stopAnimating];
[onePerson startAnimating];
[twoPerson startAnimating];
person = 2;
}
-(IBAction)personThree:(id)sender{
[fourPerson stopAnimating];
[onePerson startAnimating];
[twoPerson startAnimating];
[threePerson startAnimating];
person = 3;
}
-(IBAction)personFour:(id)sender{
[onePerson startAnimating];
[twoPerson startAnimating];
[threePerson startAnimating];
[fourPerson startAnimating];
person = 4;
}
What I'm trying to do is if this button is clicked then Person is equal to an integer value.
I don't see a problem with this code at all.
I then have another button that's using if statements.
-(IBAction)go:(id)sender{
ammountDueFloat = ([ammountDue.text floatValue]);
tipPercent1;
findAmmount = tipPercent1 * ammountDueFloat;
NSString *showAmmountText = [[NSString alloc]initWithFormat:@"$%.2f", findAmmount];
showammount.text = showAmmountText;
if (person = 1) {
showPerPerson = findAmmount / 1;
perPersonLabel.text = [[NSString alloc]initWithFormat:@"$%.2f", showPerPerson];
}
if (person = 2) {
showPerPerson = findAmmount / 2;
perPersonLabel.text = [[NSString alloc]initWithFormat:@"$%.2f", showPerPerson];
}
if (person = 3) {
showPerPerson = findAmmount / 3;
perPersonLabel.text = [[NSString alloc]initWithFormat:@"$%.2f", showPerPerson];
}
if (person = 4) {
showPerPerson = findAmmount / 4;
per开发者_运维知识库PersonLabel.text = [[NSString alloc]initWithFormat:@"$%.2f", showPerPerson];
}
else {
showPerPerson = findAmmount / 1;
perPersonLabel.text = [[NSString alloc]initWithFormat:@"$%.2f", showPerPerson];
}
}
Whenever I click the button 'go' it always assumes the value of person is the last if statement.
Any ideas?
use == to compare
if(person == 1)
{
//...
}
person = 1
It assigns 1 to person, rather than checking whether the person is equal to one. As 1 is assigned to person, this condition is always true. You need ==
operator instead of =
in if
conditions.
if (person == 1) {
} else if (person == 2) {
} // similar
I would write it as comment, but it's not convenient, so it's here
As both answers suggested, you should use equality operator, please consider:
if ( (person < 1) || (person > 4 ) {
person = 1;
}
showPerPerson = findAmmount / person;
perPersonLabel.text = [[NSString alloc]initWithFormat:@"$%.2f", showPerPerson];
instead of the whole if cases.
And if you use the if cases, you should add else after each case, otherwise the last part will be run every time person != 4:
if (person == 1) {
//..
}
else if (person == 2) {
//..
}
else if (person == 3) {
//..
}
//..
精彩评论