arin
arin

Reputation: 600

Why this code is not working?

Hi guys I wrote this code and i have two errors.

  1. Invalid rank specifier: expected ',' or ']'
  2. Cannot apply indexing with [] to an expression of type 'int'

Can you help please?

    static void Main(string[] args)
    {
        ArrayList numbers = new ArrayList();

        foreach (int number in new int[12] {10,9,8,7,6,5,4,3,2,1}) //error No.1
        {
            numbers.Add(number);
        }

        numbers.Insert(numbers.Count - 1, 75);
        numbers.Remove(7);
        numbers.RemoveAt(6);

        for(int i=0; i<numbers.Count; i++)
        {
            int number = (int) number[i]; // error No.2
            Console.WriteLine(number);
        }
    }

Upvotes: 0

Views: 552

Answers (5)

Adam Lassek
Adam Lassek

Reputation: 35505

You should be initializing the array as

new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

the compiler will set the size for you. But you're doing it the hard way. Try this:

for (int i = 10; i > 0; i-- )
{
    numbers.Add(i);
}

If you are using .Net 3.5, you can also use System.Linq.Enumerable to create a range:

IEnumerable<int> numbers = Enumerable.Range(1, 10).Reverse();

This would take the place of the ArrayList, which is pretty pointless in 3.5. Since you're just starting, the ArrayList will probably be easier to grasp at first, but keep things like Generics and IEnumerables in mind, they are very important.

Upvotes: 0

John Rudy
John Rudy

Reputation: 37850

Why not the following for #1?

    for (int x = 10; x > 0; --x)
    {
        numbers.Add(number);
    }

Despite declaring this as an int[12] (as the apparent intent?), it seems like we're only using the values from 10 to 1, inclusive. Why use a foreach in this scenario, when a for is much more clear in its intent?

Upvotes: 0

Gulzar Nazim
Gulzar Nazim

Reputation: 52178

using System;
using System.Collections;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList numbers = new ArrayList();
            foreach (int number in new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })
            {
                numbers.Add(number);
            }
            numbers.Insert(numbers.Count - 1, 75);
            numbers.Remove(7);
            numbers.RemoveAt(6);
            for (int i = 0; i < numbers.Count; i++)
            {
                int number = (int)numbers[i];
                Console.WriteLine(number);
            }
        }
    }
}

Upvotes: 3

Drew Noakes
Drew Noakes

Reputation: 310917

For 1:

foreach (int number in new int[] {10,9,8,7,6,5,4,3,2,1})

For 2:

int number = (int)numbers[i];

You are using number where you should have numbers (plural).

Upvotes: 4

Aaron Smith
Aaron Smith

Reputation: 3362

1 - You don't have to specify the length of the array just say new int[]

2 - number is just an integer, I think you're trying to access numbers[i]

Upvotes: 6

Related Questions