1) Fill a two 12 element arrays < numbers> and <compare> with random numbers fro
ID: 3846484 • Letter: 1
Question
1)Fill a two 12 element arrays <numbers> and <compare> with random numbers from1 to 50 using your defined method <ranDom>. Once filled pass array back to <main> where <main> will output both array to the console using Arrays.toString() remember to import Array class required.
import java.util.Arrays;
2) Passed this filled arrays to your second method <compareArray> which will compare each element in <compare> to every element in <numbers> to find elements that match (are numerical equal). Output both the value of the found numbers that match and their relative position in each array. Also output the total number of matches found.
3) All outputs will be to the console. There are no user inputs
Your java project name and class name will be < ArrayCompar >
Remember to use the <return> statement in the compare method to pass back to <main> the total number of “hits” (element found.)
Since these arrays are both filled with random number you may have to run it more than once to get any “hits”.
Explanation / Answer
ArrayCompar.java
import java.util.Arrays;
import java.util.Random;
public class ArrayCompar {
public static void main(String args[]) {
int numbers[] = new int[12];
int compare[] = new int[12];
ranDom(numbers, compare);
System.out.println("Numbers array: "+Arrays.toString(numbers));
System.out.println("Compare array: "+Arrays.toString(compare));
int hits = compareArray(numbers, compare);
System.out.println("Number of matches: "+hits);
}
public static void ranDom(int numbers[], int compare[]) {
Random r = new Random();
for(int i=0;i<numbers.length;i++){
numbers[i] = r.nextInt(50)+1;
compare[i] = r.nextInt(50)+1;
}
}
public static int compareArray(int numbers[], int compare[]) {
int hits = 0;
for(int i=0;i<numbers.length;i++){
if(numbers[i] == compare[i]) {
hits++;
System.out.println("Posiiton: "+i+" Number: "+numbers[i]);
}
}
return hits;
}
}
Output:
Numbers array: [50, 36, 25, 39, 35, 6, 11, 30, 17, 2, 49, 47]
Compare array: [24, 46, 42, 8, 34, 36, 12, 24, 45, 2, 42, 24]
Posiiton: 9 Number: 2
Number of matches: 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.