Miyerkules, Pebrero 8, 2012

FILE WRITING AND SORTING (Main Program)

import java.io.*;
import utils.*;
public class WriteToFile {
    static Student[] students;
    public static void main(String[]args) throws Exception
    {
        FileWriter fw= new FileWriter("students.dat", true);
        BufferedWriter out= new BufferedWriter(fw);
        Input input= new Input();


        int count;

        //ask the number of students
        System.out.println("How many students?");
        count= input.getInt();
        //initialize the students array size
        students= new Student[count];
        //instanstiate each array element
        for(int i=0; i<students.length; i++)
        {
            students[i]= new Student();
        }

        //Student's details
        for(int i=0; i<count; i++)
        {
            System.out.print("Enter Name: ");
            students[i].setName(input.getString());
           
            System.out.print("ID #: ");
            students[i].setId(input.getString());
           
            System.out.print("COurse: ");
            students[i].setCourse(input.getString());
           
            System.out.print("Year Level: ");
            students[i].setYear(input.getString());
            System.out.println("");
         }

         sortStudents();

        //Writing data
        for(int i=0; i<count; i++)
        {
            out.write(students[i].getName());
            out.write(",");
            out.write(students[i].getId());
            out.write(",");
            out.write(students[i].getCourse());
            out.write(",");
            out.write(students[i].getYear());
           
            out.newLine();


        }
        out.close();


    }

public static void sortStudents()
        {
            int locOfSmallest;
            Student temp;

            for(int step=0; step<students.length; step++)
                {
                    //find the location of the smallest element from the array[step] to the end of the array
                    locOfSmallest= step;

                        for(int loc=step; loc<students.length; loc++)
                            {
                                if(students[loc].getName().compareTo(students[locOfSmallest].getName())<0)
                                {
                                    locOfSmallest= loc;
                                }
                            }
                    //exchange students[step] with students[locOfSmallest]
                    temp= students[step];
                    students[step]= students[locOfSmallest];
                    students[locOfSmallest]=temp;

                }
        }
}

Walang komento:

Mag-post ng isang Komento