Hey guys, I'm new to taking Java and this stuff really stump me. I have mini assignment by my teacher to: *make 2 arrays with 20 random #s, *merge them into a single array, *put new array (of 40 random numbers) and put them in ascending order W/O DUPLICATES, and *make a counter that counts how many times the program goes through a loop.
The below is my code:
I'm having trouble with the non duplicate part, which I highlighted. I'm trying to get the program to print out 40 numbers total in ascending order and non duplicated. This is as far as I've gotten. Output would always be something like this:Quote:
import javax.swing.JOptionPane;
public class MergeArrays
{
public static void main (String args [])
{
int array1 [] = new int [21];
int array2 [] = new int [21];
int array3 [] = new int [41];
String output1 = "";
String output2 = "";
String output3 = "";
for(int a = 1; a <= 20; a++) {
array1 [a] = (int)(Math.random()*100+1);
array2 [a] = (int)(Math.random()*100+1); //generating numbers for array1 and array2
array3 [a] = array1 [a];
array3 [a+20] = array2 [a]; //combining array1 and array2 into array3
}
for(int a = 1; a < 40; a++)
for(int b = a + 1; b <= 40; b++) {
if(array3[a] > array3[b]) {
array3 [0] = array3 [a];
array3 [a] = array3 [b];
array3 [b] = array3 [0];
} //ascending order arranging loop
if(array3[a] == array3[b]) {
array3[b] = (int)(Math.random()*100+1);
} //replace duplicates with new number
}
for(int a = 1; a < 20; a++) {
output1 = output1 + array1[a] + ", ";
output2 = output2 + array2[a] + ", ";
} output1 = output1 + array1[20];
output2 = output2 + array2[20]; //original arrays output loop
for(int a = 1; a < 40; a++) {
output3 = output3 + array3[a] + ", ";
} output3 = output3 + array3[40]; //sorted array output loop
JOptionPane.showMessageDialog(null, "First Set of 20 #s: " + output1 + "\nSecond Set of 20 #s: " + output2
+ "\nBoth Set Combined(Ascending Order): " + output3,
"Random Number Generator",
JOptionPane.PLAIN_MESSAGE);
}
}
Notice how it's all ascending except for duplicates that was replaced...Quote:
First Set of 20 #s: 38, 21, 100, 14, 54, 11, 31, 85, 38, 25, 43, 20, 77, 25, 39, 78, 30, 61, 82, 62
Second Set of 20 #s: 17, 98, 67, 42, 58, 64, 7, 62, 75, 87, 20, 52, 63, 23, 48, 54, 43, 70, 35, 9
Both Set Combined(Ascending Order): 7, 9, 11, 14, 17, 4, 20, 21, 23, 25, 30, 31, 35, 38, 39, 42, 43, 48, 52, 54, 58, 60, 61, 18, 62, 26, 63, 64, 67, 70, 74, 75, 77, 78, 82, 84, 85, 87, 98, 100
Please tell me what I did wrong and how to correct it, a more efficient method(not anything complicated that a beginner should know), etc. Thank you!
ALSO: if you know how to make a counter that counts the amount of loops my script has to go through, please share as well! thanks in advance!
