Assignment 9 - Solution

File Sorting (Vectors)

Here's one possible solution to the problem.
import java.util.*; 
import java.io.*;
import java.awt.*; 
import BreezyGUI.*; 
 
class Homework9 extends GBFrame {
 
  Label      fileLabel  = addLabel     ("File name: ", 1, 1, 1, 1); 
  TextField  fileField  = addTextField ("input.dat"  , 1, 2, 1, 1); 
  Button     doReport   = addButton    ("Sort asc."  , 2, 1, 2, 1); 
  TextArea   outputArea = addTextArea  (""           , 3, 1, 2, 3); 
 
  Vector v; 
 
  public Homework9() { 
    setTitle("Sorting in Ascending Order"); 
  } 
 
  public void buttonClicked(Button buttonObj) {
    String fileName = fileField.getText(); 
    try {
      FileInputStream f = new FileInputStream(fileName);
      readAndProcessData(f); 
      f.close(); 
    } catch (IOException e) { 
      messageBox("File not opened:\n  " + e.toString()); 
    } 
  } 
 
  private void readAndProcessData(FileInputStream stream) {
    StreamTokenizer reader = 
      new StreamTokenizer(
        new BufferedReader(
          new InputStreamReader(
            stream))); 
    v = new Vector(); 
    try {
      String data = ""; 
      outputArea.setText(data); 
      reader.nextToken(); 
      while (reader.ttype != StreamTokenizer.TT_EOF) {
        if (reader.ttype == StreamTokenizer.TT_NUMBER) {
          v.addElement(new Integer((int)(reader.nval))); 
          outputArea.append((int)(reader.nval) + " "); 
          reader.nextToken(); 
        } 
      } 
      outputArea.append("\n"); 
      sortAndPrint(); 
    } catch (Exception e) {
      messageBox("Error: " + e.toString()); 
    }
  } 
 
  private void sortAndPrint() {
    outputArea.append("\nSorted:\n"); 
    for (int i = 0; i < v.size() - 1; i++) {
      for (int j = i; j < v.size(); j++) { 
        if (((Integer)v.elementAt(i)).intValue() > 
            ((Integer)v.elementAt(j)).intValue()) {
          Object aux = v.elementAt(i); 
          v.setElementAt(v.elementAt(j), i); 
          v.setElementAt(aux, j); 
        } 
      } 
    }
    for (int i = 0; i < v.size(); i++) {
      outputArea.append(((Integer)v.elementAt(i)).intValue() + " "); 
    }
  } 
 
  public static void main(String[] args) {
    Frame frm = new Homework9(); 
    frm.setSize(250, 200); 
    frm.setVisible(true); 
  } 
}