Advertisement
fayimora

Using array Lists

Apr 11th, 2011
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3. class StudentNames
  4. {
  5.     private ArrayList<String> names;
  6.     private int numOfStudents;
  7.    
  8.     public StudentNames(int numOfStudents)
  9.     {
  10.         names = new ArrayList<String>(3);
  11.         this.numOfStudents = numOfStudents;
  12.     }
  13.    
  14.     void getName() throws Exception {
  15.         Scanner cin = new Scanner(new InputStreamReader(System.in));
  16.         for (int i=0; i<numOfStudents; i++) {
  17.             System.out.println("Student number " + (i+1) + "'s name please!");
  18.             names.add(cin.next());
  19.         }
  20.         System.out.println("Thanks for the names!");
  21.     }
  22.    
  23.     void writeToScreen() throws Exception {
  24.         int i=0;
  25.         for(String s: names)
  26.             System.out.println( (i+1) + ": " + s );
  27.     }
  28.    
  29.     void writeToFile(String filename) throws Exception {
  30.         PrintWriter writer = new PrintWriter(filename);
  31.         for(String s: names)
  32.             writer.println(s);
  33.     }
  34.    
  35.     public static void main(String[] args) throws Exception {
  36.         StudentNames sn = new StudentNames(3);
  37.         try{
  38.             sn.getName();
  39.             sn.writeToScreen();
  40.             sn.writeToFile("abc.txt");
  41.         }catch(IOException e){
  42.             System.out.println(e.getMessage());
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement