[xcodeitalia] Parser 0.2

  • From: Claudio Mezzasalma <claudio.mezzasalma@xxxxxxxxx>
  • To: xcodeitalia@xxxxxxxxxxxxx
  • Date: Mon, 17 Mar 2008 18:27:21 +0100

Ho trovato un bug nel caso l'espressione iniziasse con una x senza coefficiente, risolto. La modifica inserita per risolvere questo, comunque, dovrebbe farci riflettere sull'inadeguatezza dell'NSScanner per fare cose così.


I found a bug when the expression starts with an x without a coefficient. However, the fix introduced should make us think about the inadequacy of NSScanner to make such things.

@implementation functionParser
- (IBAction)parseFunction:(id)sender; {
        NSMutableArray *factorsArray = [NSMutableArray array];
        NSMutableArray *functionArray = [NSMutableArray array];
        int exponent;
        float coefficient;
        NSLog (@"%@",[functionTextField stringValue]);
NSString *functionString = [NSString stringWithString: [functionTextField stringValue]]; NSScanner *functionScanner = [NSScanner scannerWithString:functionString];
        [functionScanner setScanLocation: 2];
        while ([functionScanner isAtEnd] == NO)
        {
                if ([functionScanner scanFloat: &coefficient]) {
                        if([functionScanner scanString: @"x^" intoString:NULL]) 
{
                                [functionScanner scanInt: &exponent];
                        }
                        else if ([functionScanner scanString: @"x" 
intoString:NULL]) {
                                exponent = 1;
                        }
                        else {
                                exponent = 0;
                        }
[factorsArray insertObject: [NSNumber numberWithFloat:coefficient] atIndex: 0]; [factorsArray insertObject: [NSNumber numberWithFloat:exponent] atIndex: 1];
                [functionArray addObject: factorsArray];
                }
                else {
                        coefficient = 1;
                        if([functionScanner scanString: @"x^" intoString:NULL]) 
{
                                [functionScanner scanInt: &exponent];
                        }
                        else if ([functionScanner scanString: @"x" 
intoString:NULL]) {
                                exponent = 1;
                        }
                        else {
                                exponent = 0;
                        }
[factorsArray insertObject: [NSNumber numberWithFloat:coefficient] atIndex: 0]; [factorsArray insertObject: [NSNumber numberWithFloat:exponent] atIndex: 1];
                        [functionArray addObject: factorsArray];
                }
        }
        //return functionArray;
}
@end

Other related posts: