Why this code is not working?
Question
Hi guys I wrote this code and i have two errors.
- Invalid rank specifier: expected ',' or ']'
- 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);
}
}
Solution
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);
}
}
}
}
OTHER TIPS
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]
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).
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?
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.