-1

I am generating a random equation say like 2*3+4..... and using DDMathparser to evaluate it. Here I have a class method which is supposed to return a random equation(stored inside a mutable array) only if it evaluates to a integer. however it keeps returning Null and i can't figure out why. Please help me out.!

#import "Equation.h"
#import "DDMathParser.h"

@implementation Equation
-(NSMutableArray*)randEquation{
    NSMutableArray* usableEquation=[[NSMutableArray alloc]init];
    while(1){
    NSArray *nums = @[@"1", @"2", @"3", @"4", @"5",@"6",@"7",@"8",@"9"];
    unsigned index1=arc4random()%9;
    NSString* num = [NSString stringWithFormat:@"%@", [nums objectAtIndex:index1]];
    NSArray *symbols = @[@"+", @"-", @"*", @"/"];
    unsigned index=arc4random()%4;
    NSString* symb = [NSString stringWithFormat:@"%@", [symbols objectAtIndex:index]];
        NSMutableArray *arrayOfSymbolsAndNumbers = [[NSMutableArray alloc] init];
        for( int i=0;i<=10;i++){
            if (i%2==0) {
                [arrayOfSymbolsAndNumbers addObject:num];
            }
            else{
                [arrayOfSymbolsAndNumbers addObject:symb];
            }

        }
        NSMutableString *stringOfSymbolsAndNumbers=[[NSMutableString alloc]init];
        for (NSObject * obj in arrayOfSymbolsAndNumbers)
        {
            [stringOfSymbolsAndNumbers appendString:[obj description]];


        }
        usableEquation=arrayOfSymbolsAndNumbers;
        NSNumber *result=[stringOfSymbolsAndNumbers numberByEvaluatingString];
        float resultFloat = [result floatValue];
        float checker=resultFloat;
        if (floor(checker)==checker) {
            break;
        }
        else{
            continue;
        }
    }
    return usableEquation;
}

@end
  • 1
    How are you checking the `nil` return? What debugging have you done? – Wain Jun 28 '14 at 11:10
  • In the story board i tried NSlog with the returned array by using NSLog(@"The content of array is%@",[equation randEquation]); and the output on my console is :The content of array is(null). Also I am setting the titles of some buttons to the content of that array and the titles are not being set. – Dipankar Choudhary Jun 28 '14 at 11:12
  • In the previous comment in: NSLog(@"The content of array is%@",[equation randEquation]); "equation is just an instance of my class "Equation". – Dipankar Choudhary Jun 28 '14 at 11:17
  • Learn how to debug. Start at the point of the exception, figure out which value is nil, and work backwards to where that value is generated. – Hot Licks Jun 28 '14 at 11:48

1 Answers1

0

NSLog(@"The content of array is%@",[equation randEquation]);

Based on your code, for this log to output The content of array is(null) means that equation is nil. Your randEquation (while not efficient) looks ok, the problem is that you haven't created the equation instance when you run the log statement.

Wain
  • 118,658
  • 15
  • 128
  • 151