I’m brand new at programming and For my first attempt at an app, i’m writing a basic calculator. Right now, I can make it do calculate using all 4 operators (+,-,*,/), but if I press equals a second time it crashes. How do I make it run the calculation again? For example, if i enter “2+2=4”, how do i press equals a second time to produce “6”, and then a third time to produce “8” and so on…
Here is what I have so far. I’m using a switch statement.
-(void)equalsButton:(id)sender
{
second = [display.text integerValue];
int result;
NSArray* components;
switch (operator)
{
case 0:
components = [display.text componentsSeparatedByString:@"+"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first + second;
break;
case 1:
components = [display.text componentsSeparatedByString:@"-"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first - second;
break;
case 2:
components = [display.text componentsSeparatedByString:@"*"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first * second;
break;
case 3:
components = [display.text componentsSeparatedByString:@"/"];
first = [(NSString*)[components objectAtIndex:0] integerValue];
second = [(NSString*)[components objectAtIndex:1] integerValue];
result = first / second;
break;
}
NSString * result1 = [NSString stringWithFormat:@"%i",result];
display.text = result1;
}
From what I’m gathering, you are using that display field as both an input and an output. So when you compute the first time, it now has the result only and you lost the operator and second operand, which you are trying to re-apply to the result.
So I would say that one thing you could do if you don’t want to make too many changes is to store the operator and the second operand in instance variables every time you compute the result. That way, if you can’t determine the operator, it means you want to recall the last one. So essentially it would be adding a new case in your switch statement for:
display.textas the first operandOnce you get to that point, you will probably want to merge redundant code into an
evaluate:(int)operator a:(int)a b:(int)bmethod or something along those lines so you don’t have to repeat all the eval code for all the operators in that new case block.update
I don’t have XCode on my work computer so I can’t try it, plus I don’t have the rest of your code, but try this. It should work for +. If it does, replicate for the other operators.