Friday, November 16, 2007

PrintingDistinctNumbers

6.5** (Printing distinct numbers) Write a program that reads in ten numbers and displays distinct numbers (i.e., if a number appears multiple times, it is displayed only once). Hint: Read a number and store it to an array if it is new. If the number is already in the array, discard it. After the input, the array contains the distinct numbers.
===
PrintingDistinctNumbers.java
===
import javax.swing.JOptionPane;

public class PrintingDistinctNumbers {
public static void main(String[] args) {
final int ARRAY_LIMIT = 10;
int[] arrayInput = new int[ARRAY_LIMIT];

for (int i = 0; i < arrayInput.length; i++) {
String arrayInputString = JOptionPane.showInputDialog("Enter a number:");
int arrayInputVal = Integer.parseInt(arrayInputString);
int searchVal = PrintingDistinctNumbers.linearSearch(arrayInput, arrayInputVal);
if (searchVal == -1)
arrayInput[i] = arrayInputVal;

}
for (int j = 0; j < arrayInput.length; j++) {
if (arrayInput[j] != 0)
System.out.print(arrayInput[j] + " ");
}
}


public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++) {
if (key == list[i])
return i;
}
return -1;
}
}

No comments: