loop though a array then if and then output result?
i have a little problem, in the code below (C#) it loops thought the arrays, it then check if the user_id has a user_post greater than 50, it then writ开发者_如何转开发e the user_id, the expected outcome is
12
13
but the actual output is
12
12
12
whats wrong with the code? I tried a standard for loop but could not get it right?
int[] user_id = new int[64];
int[] group_id = new int[64];
int[] user_post = new int[64];
//user 55
user_id[0] = 10;
group_id[0] = 8;
user_post[0] = 4;
//user56
user_id[1] = 11;
group_id[1] = 2;
user_post[1] = 15;
//user57
user_id[2] = 12;
group_id[2] = 2;
user_post[2] = 55;
//user58
user_id[3] = 13;
group_id[3] = 2;
user_post[3] = 56;
foreach (int i in group_id)
{
if (group_id[i] == 2)
if (user_post[i] > 50)
Console.WriteLine(Convert.ToString(user_id[i]));
}
Console.WriteLine("Press any key too continue...");
Console.ReadLine();
// continue...
Because you have an if statement that only checks for 2
if (group_id[i] == 2)
where as "i" is not a counter instead the element from the foreach loop. and items at 2 & 3rd position have 2 group id so it alway ends like this:
if (group_id[8] == 2) //false
if (group_id[2] == 2) //true
if (group_id[2] == 2) //true
Instead of that vague code you should have your loop as this:
for(int i = 0 ; i< 64 ; i++)
{
if (group_id[i] == 2)
{
if (user_post[i] > 50)
Console.WriteLine(Convert.ToString(user_id[i]));
}
}
in your foreach statement, i
takes on the values stored in your group_id array - 8, 2, 2, 2
In your if
and output statements, your are using this value as an index into the arrays
So, your if
statements end up doing this:
if(group_id[8])...
if(group_id[2])...
if(group_id[2])...
if(group_id[2])...
You are only examining elements 8 and 2 in your arrays.
Use a for
loop to iterate through the array indexes
The for
syntax is as follows:
for (int i = 0; // incremental variable
i < 100; // determining a limit
++i) // increment the variable
While foreach
works like this:
foreach (var element // the element itself, not an index
in
elementCollection) // iterating through the collection
You're looping around the wrong array with the for each statement. You should loop using the regular for statement instead like this:
for (int i = 0;i < user_post.Length; i++)
{
if (user_post[i] > 50 && group_id[i] == 2)
{
Console.WriteLine(Convert.ToString(user_id[i]));
}
}
foreach (int i in group_id)
is wrong, you must use:
for(int i = 0; i < group_id.Length; i++)
because with the former you're using the values in group_id
as indexes of your arrays.
BTW, I'd suggest you to create a class e.g. Info
like:
class Info
{
public int GroupId {get; set;};
public int UserId {get; set;};
public int PostId {get; set;}
}
this would allow you to create one array only (i.e. Info[]
) and avoid possible errors due to different lenghts of the 3 arrays...
精彩评论