Is there a more efficient way to create the three files and write to those files using BufferedOutput
and BufferedWiter
I/O? The code works, but I thought there has to be a more compact way to accomplish this.
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class SortStudent
{
public static void main(String[] args)
{
//variables for processing
Path fileOut1 = Paths.get("Honors_Students.txt");
Path fileOut2 = Paths.get("Good_Standing.txt");
Path fileOut3 = Paths.get("Probation_Students.txt");
String recOut;
String delimiter = ",";
Scanner input = new Scanner(System.in);
final int QUIT = 999;
//data class record
Student student = new Student();
//input.output may generate exceptions
try
{
//Setup the 3 files to be used for output
OutputStream output1 =
new BufferedOutputStream(Files.newOutputStream(fileOut1, CREATE));
OutputStream output2 =
new BufferedOutputStream(Files.newOutputStream(fileOut2, CREATE));
OutputStream output3 =
new BufferedOutputStream(Files.newOutputStream(fileOut3, CREATE));
BufferedWriter writer1 =
new BufferedWriter(new OutputStreamWriter(output1));
BufferedWriter writer2 =
new BufferedWriter(new OutputStreamWriter(output2));
BufferedWriter writer3 =
new BufferedWriter(new OutputStreamWriter(output3));
BufferedWriter writer = null;
//initial read for indefinite repetition
System.out.print("Enter Student's ID number or 999 to quit: ");
student.setID(input.nextInt());
//sentinel controlled loop
while (student.getID() != QUIT)
{
//get Student First Name
System.out.print("Enter Student's First Name: ");
student.setFirstName(input.next());
//get Student Last Name
System.out.print("Enter Student's Last Name: ");
student.setLastName(input.next());
//get Student GPA
System.out.print("Enter Student's Grade Point Average: ");
student.setgpa(input.nextDouble());
//if gpa is 3.6 or> write to Honors Student
if (student.Honors())
writer=writer1;
//if gpa is >=2.0 and >3.5 write to Good Standing Student
else if (student.Good_Standing())
writer=writer2;
//if gpa is <2.0 write to Probation Student
else if (student.Probation())
writer=writer3;
//out of range
else
continue;
//build the record
recOut = student.getID() + delimiter
+ student.getFirstName() + delimiter
+ student.getLastName() + delimiter
+ student.getgpa();
//write the record
writer.write(recOut, 0, recOut.length());
writer.newLine();
//subsequent read for indefinite repetition
System.out.print("Enter a Student's ID number or 999 to quit: ");
student.setID(input.nextInt());
}
//close all files
writer1.close();
writer2.close();
writer3.close();
}
catch(Exception e)
{
System.out.println("<<An exception has occurred.>> ");
System.out.println(e.getMessage());
}
}
}