import java.io.*; //the File class import java.util.*; //ArrayList & the Scanner class in Java 1.5 public class Widget_ArrayList { public static void main(String[] args) throws Exception { ArrayList apple = input("widget.txt"); sort(apple); output(apple); } public static ArrayList input(String filename) throws Exception { Scanner infile = new Scanner( new File(filename) ); ArrayList array = new ArrayList(); while(infile.hasNext()) // read all data in the file { int x = infile.nextInt(); int y = infile.nextInt(); array.add(new Widget(x, y)); } infile.close(); return array; } public static void sort(ArrayList array) { int maxPos; for(int k = 0; k < array.size(); k++) { maxPos = findMax(array, array.size() - k - 1); swap(array, maxPos, array.size() - k - 1); } } public static int findMax(ArrayList array, int upper) { int maxPos = 0; for(int j = 1; j <= upper; j++) if(array.get(j).compareTo(array.get(maxPos)) > 0) maxPos = j; return maxPos; } public static void swap(ArrayList array, int a, int b) { Comparable temp = array.get(a); array.set(a, array.get(b)); array.set(b,temp); } public static void output(ArrayList array) { for(Comparable x:array) //use the for-each loop System.out.println(x); } }