printing distinct numbers with arrays
So my code asks a user to enter 10 numbers, it then checks to see if the number is already in the array, then prints out the entered numbers in a dialog box, but does not print duplicates (i.e. if the entered numbers are 1,2,3,4,5,6,7,8,9,9- the program prints 1,2,3,4,5,6,7,8,9. Excluding extra 9).
I got it mostly working and it works fine if i try to print it in the console, but it is the dialog box that is throwing me off, as it includes the duplicate numbers.
heres the code:
Code java:
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter an integer:"));
}//end of for
checkArray (array);
JOptionPane.showMessageDialog(null, array[0] + " " + array[1] + " " + array[2] + " " + array[3] + " " + array[4] + " " + array[5] + " " + array[6] + " " + array[7] + " " + array[8] + " " + array[9]);
}//end of main
public static int checkArray(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}//end of if
if (!found)
return array[i];
//JOptionPane.showMessageDialog(null, array[0] + " " + array[1] + " " + array[2] + " " + array[3] + " " + array[4] + " " + array[5] + " " + array[6] + " " + array[7] + " " + array[8] + " " + array[9]);
}//end of for
return 1;
}//end of checkArray
}//end of class
This is where i was just going into console when it works just fine.
Code java:
if (!found)
System.out.println(array[i]);
Re: printing distinct numbers with arrays
checkArray checks to see if the number already exists, but it never does anything to the number in the array. Do you want to keep the number in the array? Currently checkArray just returns whether or not a number (any number) is duplicated. It does not remove them or do anything with the array. Therefore, when you print out every array entry, it will show all duplicate values, since you have not changed any of the values in the array. The question is, what do you want to do with the duplicate values?
1. If you want to keep them in the array and only print out the non-duplicate values, you need to create a method that goes through the array and builds a string of the values to output
2. If you do not want to preserve the values, you can zero them out and print only the non-zero values.
Re: printing distinct numbers with arrays
First of all, thanks so much for the reply! Option 2 sounds like what i want to do. Because I do not need the duplicates. However, how would I go about zeroing them out and only printing non-zero values?