Difference between revisions of "SET08112"

From Progzoo
Jump to: navigation, search
(Problem 1 - Sort a List)
(Problem 1 - Sort a List)
Line 14: Line 14:
 
*You can use java.util.Collections.sort to sort the ArrayList  
 
*You can use java.util.Collections.sort to sort the ArrayList  
 
<prog>
 
<prog>
 +
import java.util.ArrayList;
 +
import java.io.BufferedReader;
 +
import java.io.FileReader;
 +
 +
public class SortStudents{
 +
  public static void main(String[]argv) throws Exception{
 +
    ArrayList&lt;String> names = new ArrayList&lt;String>();
 +
    String line;
 +
    BufferedReader fh
 +
      = new BufferedReader(new FileReader("students.txt"));
 +
    while (null!=(line=fh.readLine()))
 +
      names.add(line);
 +
    for (String s:names)
 +
      System.out.println(s);
 +
  }
 +
}
 +
</prog>
 +
<answer>
 
import java.util.ArrayList;
 
import java.util.ArrayList;
 
import java.io.BufferedReader;
 
import java.io.BufferedReader;
Line 31: Line 49:
 
   }
 
   }
 
}
 
}
</prog>
+
</answer>
 
</question>
 
</question>

Revision as of 13:42, 26 January 2011

SET08112 ArrayList INterface Tutorial

In this tutorial you will use the ArrayList and the HashMap or TreeMap to solve some common problems.

Problem 1 - Sort a List

The file from http://www.dcs.napier.ac.uk/~cs66/SET08112/tut2/students.txt contains a list of students:

ADAMS, ROBERT
HASTIE, MARTIN
OTHIENO, JUDITH
ANDERSON, ROSS
...

Create a programme SortStudents.java that reads in this file and outputs the students in Alphabetical order.

  • You can use an ArrayList to hold the students.
  • ArrayList<String> names = new ArrayList<String>();
  • You can use java.util.Collections.sort to sort the ArrayList


[Font] [Default] [Show] [Resize] [History] [Profile]