/**
 * Asks the user for positive numbers, storing them in an array.
 * Also allows users to delete numbers from that array by entering
 * negative numbers.
 * <p>
 * This is a rather odd/contrived program, but it concisely demonstrates
 * many common idioms for processing arrays.
 *
 * @author Zach Tomaszewski
 */
public class StoredNumbers {

  public static void main(String[] args) {

    java.util.Scanner keybd = new java.util.Scanner(System.in);

    int[] nums = new int[5];
    int count = 0;  //will keep track of the next open cell in nums array

    System.out.println("The program tracks the positive integers you enter.");
    System.out.println("You can enter a negative number to delete the " +
        "corresponding positive value.");
    System.out.println("Enter 0 to quit.");

    int input = 1;
    while (input != 0) {

      //print the numbers so far on one line
      System.out.println();
      System.out.print("Numbers: ");
      for (int i = 0; i < count; i++) {
        System.out.print(nums[i] + " ");
      }
      System.out.println();

      try {
        //ask user to enter another number
        System.out.print("Enter a number (0 to quit): ");
        input = keybd.nextInt();

        if (input > 0) {
          //check if the array is full
          if (count == nums.length) {
            //current array is full, so double its size
            int[] temp = new int[nums.length * 2];
            for (int i = 0; i < nums.length; i++) {
              temp[i] = nums[i];
            }
            nums = temp;
          }

          //add entered value to the array
          nums[count] = input;
          count++;

        }else if (input < 0) {
          //delete positive version of input
          input = input * -1;  //convert negative input to positive

          //find the index of a value already in the array
          int found = -1;
          for (int i = 0; i < count; i++) {
            if (nums[i] == input) {
              found = i;
              break;  //stop looping on first match found
            }
          }
          if (found == -1) {
            //did not find the item the user asked to delete
            System.out.println("Could not find " + input + " to delete.");
          }else {
            //delete element at index found, shifting later elements down/left
            for (int i = found; i < count - 1; i++) {
              nums[i] = nums[i + 1];
            }
            count--;
          }
        }
      }catch (java.util.InputMismatchException e) {
        System.out.println("Sorry, but you must enter an integer.");
        keybd.nextLine(); //clear input stream
      }
    }//end input loop

  }//end main

}//end class

