Comparing elements in two arrays
Good afternoon everyone.
I am trying to compare the int elements in two arrays for a homework assignment. I just need to confirm something - I do not need any actual code answer posted, ok?
I am trying to see which array has the higher number overall when comparing each element. Does ArrayA have more "wins" than ArrayB, essentially.
This is my code
Code:
public class Compare_Two_Arrays
{
public static void main(String[] args)
{
// the integer counters are set
int A_wins = 0;
int B_wins = 0;
// below sets up the two integer arrays that we will compare
int[] intArrayA = new int[]{1, 2, 11, 12, 15, 16};
int[] intArrayB = new int[]{3, 4, 7, 8, 17, 18};
for (int i = 0; i <= intArrayA.length-1; i++)
{
for(int j = 0; j <= intArrayB.length-1; j++)
{
if (intArrayA[i] > intArrayB[j])
{
A_wins = A_wins +1;
}
else if (intArrayA[i] < intArrayB[j])
{
B_wins = B_wins + 1;
}
}
if( A_wins > B_wins)
{
System.out.println(" A has the majority of wins");
}
else
{
System.out.println(" B has the majority of wins");
}
}
}
}
This is what I get :
Code:
B has the majority of wins
B has the majority of wins
B has the majority of wins
B has the majority of wins
B has the majority of wins
B has the majority of wins
And this is where the coding error lies (since the answer above is wrong), I think.
Code:
for(int j = 0; j <= intArrayB.length-1; j++)
Basically, its comparing every iteration of the 2nd array to just the first element in the first array, right?
Can you confirm my suspicions?
Thanks again to all those who look this over.
Re: Comparing elements in two arrays
You've got *nested* for loops, so your first of all looping through the first array, and then inside of this loop, you're using another for loop to compare the current first array item with every item in the second array. I suspect that you want to use only one for loop and compare arrayA[i] item with arrayB[i] item.
Re: Comparing elements in two arrays
I see....
I have not done that before, truth be told.
use one for loop for the length of the array (since they are the same length), and compare each array at the element, as it loops.
I will try that.
Fubarable - thank you.
This is gonna be pretty fun to try out.
Re: Comparing elements in two arrays
Quote:
Originally Posted by
Adomini
I see....
use one for loop for the length of the array (since they are the same length), and compare each array at the element, as it loops.
I will try that.
Fubarable - thank you.
This is gonna be pretty fun to try out.
And I'm betting that you will succeed. You're welcome and best of luck!