Saturday, October 22, 2011

Array


Java lessons


(Duplicate Elimination) Use a one-dimensional array to solve the following problem: Write
an application that inputs five numbers, each between 10 and 100, inclusive. As each number is
read, display it only if it is not a duplicate of a number already read. Provide for the “worst case,” in
which all five numbers are different. Use the smallest possible array to solve this problem. Display
the complete set of unique values input after the user enters each new value.

import java.util.Scanner;
//This program reads in 5 unique numbers.

public class DulpElimination {


       public static void main (String args[]) {
              int arr[] = new int [5];
              Scanner input = new Scanner(System.in);
              int count = 0;

              while (count < arr.length) {
                     System.out.println("Enter number: ");
                     int temp = input.nextInt();

                     // Ensure the input is within the valid range
                     if (temp >= 10 && temp <= 100) {
                           boolean flag = false; // flag to indicate whether the number was read already.

                           // compare the current number with the numbers in the array
                           for (int i = 0; i < count; i++) {
                                  // if the number duplicate, set the flag
                                  if (temp == arr[i]) {
                                         flag = true;
                                  }
                           }

                           if (!flag) { // add number to the array if it's not a duplicate
                                  arr[count] = temp;
                                  count ++;
                                  System.out.println(temp + " is added.");
                           }
                           else {
                                  System.out.println(temp + " has been entered.");
                           }
                     }
                     else {
                           System.out.println("Numbers should be between 10 and 100");
                     }

                     // displaying all numbers currently in the array.
                     System.out.println("The numbers currently in the array are:");
                     for (int i = 0; i < count; i++ ) {
                           System.out.print(arr[i] + " ");
                     }

                     System.out.println("\n");
              }
       }
}