import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.ArrayList;

/**
 * This class demonstrates how to use an ArrayList.
 * It reads in 3 numbers from the user, swaps the last two,
 * and then prints out the results.  It this all twice: once using
 * an array and then again using an ArrayList.
 *
 * @author Zach Tomaszewski
 * @version 06 Apr 2010
 */
public class ReadingInNumbers {

  public static void main(String[] args) {
    Scanner keybd = new Scanner(System.in);

    int[] array = new int[3];
    for (int i = 0; i < array.length; i++) {
      try {
        System.out.print("Enter an integer: ");
        array[i] = keybd.nextInt();
      }catch (InputMismatchException ime) {
        System.out.println("That was not an integer.  Please try again.");
        keybd.nextLine();  //clear stream
        i--;  //repeat for this index again
      }
    }

    //swap last two elements
    int temp = array[1];
    array[1] = array[2];
    array[2] = temp;

    //print array
    System.out.println("Your numbers (after swapping the last two): ");
    System.out.println(java.util.Arrays.toString(array));
    System.out.println();


    //now do it all again, with an ArrayList!

    //since list will hold primitive values, need to use <wrapper class name>
    ArrayList<Integer> list = new ArrayList<Integer>();

    while (list.size() < 3) {
      try {
        System.out.print("Enter an integer: ");
        list.add(keybd.nextInt());
      }catch (InputMismatchException ime) {
        System.out.println("That was not an integer.  Please try again.");
        keybd.nextLine();  //clear stream
      }
    }

    //swap last two elements  (temp variable already declared as int above)
    temp = list.get(1);  //example of auto-unboxing Integer to int
    list.set(1, list.get(2));
    list.set(2, temp);       //example of auto-boxing from int to Integer

    //print array
    System.out.println("Your numbers (after swapping the last two): ");
    System.out.println(list);
    System.out.println();
  }
}
