Question

Trying to create a simple calculator for +, -, *, and / functions.

I've created a segmented box to pass an operator and two text fields to collect the values.

If 

txtBox1.text = 5

and


txtBox2.text = 9

and 

Operator = +

In xcode, how to I take the string I've created from this (5+9) and run the mathematics and return to the txtBoxAnswer.text?

Here is what I have:

NSString *theMath;

- (IBAction)operatorSelected:(id)sender {
    NSArray *theOperatorInCode =[NSArray arrayWithObjects:@"+",@"-",@"*",@"/", nil];
    theMath = theOperatorInCode[_theOperator.selectedSegmentIndex];
}

- (IBAction)pressTheEquals:(id)sender {
    int first = [self.theFirstNumber.text floatValue];
    int second = [self.theSecondNumber.text floatValue];
    **NSString *answer = [NSString stringWithFormat: @"%d,%@,%d",first,theMath,second];**
}

Trying to take NSString Answer and put that string into a math equation.

No correct solution

OTHER TIPS

Very simple, indeed!

NSString *string1 = txtBox1.text;
NSString *string2 = txtBox2.text;

int number1 = [string1 intValue];
int number2 = [string2 intValue];

if([Operator isEqualToString:@"+"]) {
    int result = number1 + number2;
    txtBoxResult.text = [NSString stringWithFormat:@"%d", result];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top