Frage

I want to display every factor of a number typed in a textfield to achieve this I tried using an array. But I am always getting the error 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' . Any suggestions to eliminate this error?

       NSMutableArray *array;
        array = [NSMutableArray arrayWithCapacity:100];

        for (factorsNumber=1; factorsNumber<=number; factorsNumber++) {
            if (number%factorsNumber == 0) {
                [array addObject:[NSString stringWithFormat:@"%d", factorsNumber]];
            }

        }

        for (int i = 0; i <= [array count]; i++) {
            factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]];
        }
War es hilfreich?

Lösung

for (int i = 0; i <= [array count]; i++) {

should be

for (int i = 0; i <= [array count] - 1; i++) {

or

for (int i = 0; i < [array count]; i++) {

The valid indices of an n-element array are 0 to n-1.

Andere Tipps

In your for loop, remove the = so that it reads:

for (int i = 0; i < [array count]; i++) 

you problem is here:

for (int i = 0; i < [array count]; i++) { // < instead of <=
    factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]];
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top