Difference between revisions of "SET08112"

From Progzoo
Jump to: navigation, search
(SET08112 ArrayList INterface Tutorial)
 
(30 intermediate revisions by the same user not shown)
Line 1: Line 1:
==SET08112 ArrayList Interface Tutorial==
+
==SET08112 - Algorithms and Data Structure==
In this tutorial you will use the ArrayList and the HashMap or TreeMap to solve some common problems.
+
*[[ArrayList Tutorial]]
 
+
*[[Recursion Tutorial]]
==Problem 1 - Sort a List==
+
*[[Finite State Machines Tutorial]] and [[Finite State Machine|FSM from lecture]]
<question className="SortStudents" title="Using Sort" copyfile="students.txt">
+
*[[Assessment 2011 Tornado]]
The file  from http://www.dcs.napier.ac.uk/~cs66/SET08112/tut2/students.txt  contains a list of students:
+
*[[Recursive Descent Parsers]]
ADAMS, ROBERT
+
*[[Tree Tutorial]]
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&lt;String> names = new ArrayList&lt;String>();
+
*You can use [http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29 java.util.Collections.sort] to sort the ArrayList
+
<hint>
+
Add this line after you have filled the ArrayList but before you print it.
+
java.util.Collections.sort(names);
+
</hint>
+
<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.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);
+
    java.util.Collections.sort(names);
+
    for (String s:names)
+
      System.out.println(s);
+
  }
+
}
+
</answer>
+
</question>
+

Latest revision as of 09:37, 2 March 2012

SET08112 - Algorithms and Data Structure