In: Computer Science
CODE IN JAVA
Create a class Student includes name, age, mark and necessary methods. Using FileWriter, FileReader and BufferedReader to write a program that has functional menu:
Menu -------------------------------------------------
Your choice: _ |
+ Save to File: input information of several students and write that information into a text file, each student in a line (use tabs to separate the fields)
+ Read File: read and display information of students
The program is given below. The comments are provided for the better understanding of the logic. Please note to execute the options in order. For example, you have to add a list of students first, then load that and then go for displaying records in order by Name, Mark etc.
Also the sort comparison is case sensitive. Rob is different from rob.
import java.io.*;
import java.util.*;
public class Student {
//Declare private variables to store name, age and mark.
private String name;
private int age;
private int mark;
//Hard code filename. This is the file where the student information will be stored.
private static String FileName = "student.txt";
//The list of Students will be stored in this array list.
private static ArrayList<Student> studentList = new ArrayList<Student>();
//Getter methods for Name and Mark. This is used for sorting the records based on Name and Mark.
public String GetName() {
return name;
}
public int GetMark() {
return mark;
}
//Default Student constructor.
public Student() {
}
//Constructor to accept a record. This is a line and the fields will be separated by tab character.
public Student(String record) {
//Split the line based on tab character and store it in the fields.
//For age and mark convert to int before storing.
String[] fields = record.split("\t");
name = fields[0];
age = Integer.parseInt(fields[1]);
mark = Integer.parseInt(fields[2]);
}
//This function will accept name, age and mark and store it as a record in the file.
public void addRecord(String name, int age, int mark) {
try {
//Format the 3 variables, separate it by tab character and store it in the file.
BufferedWriter bw = new BufferedWriter(new FileWriter(FileName, true));
bw.write(name + "\t" + age + "\t" + mark + "\n");
bw.close();
}
catch(IOException e) {
//Handle any Exception related to file operation.
System.out.println(e.toString());
}
}
//This function will accept Student details from the command line and calls the adddRecord function for each student.
public static void addRecords() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Get how many students.
System.out.print("How many Student records to add? ");
int noOfRecords = Integer.parseInt(br.readLine());
//Loop for the number of students.
for(int i = 1; i <= noOfRecords; i++) {
//Get the details for each student and call the add record function.
System.out.println("\nEnter the details of Student # " + i);
System.out.print("Name?");
String name = br.readLine();
System.out.print("Age?");
int age = Integer.parseInt(br.readLine());
System.out.print("Mark?");
int mark = Integer.parseInt(br.readLine());
Student s = new Student();
s.addRecord(name, age, mark);
}
}
//This function reads the student details from the file and add it to the array list.
public static void loadRecords() {
try {
File f = new File(FileName);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
//clear existing information from the arraylist.
studentList.clear();
String line;
//Loop through line by line with the file contents.
while((line = br.readLine())!= null) {
//create a student object for each line and add it to arraylist.
studentList.add(new Student(line));
}
fr.close();
}
catch(IOException e) {
//Handle any file exception.
System.out.println(e.toString());
}
}
//Sort based on Name in descending order and display the student information.
public static void displayByName() {
Collections.sort(studentList, new SortHandlerByName());
for (Student s : studentList)
System.out.println("Name: " + s.name + ", Age: " + s.age + ", Mark: " + s.mark);
}
//Sort based on Mark in descending order and display the student information.
public static void displayByMark() {
Collections.sort(studentList, new SortHandlerByMark());
for (Student s : studentList)
System.out.println("Name: " + s.name + ", Age: " + s.age + ", Mark: " + s.mark);
}
//main function
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Start a loop for getting options from the user. the exit condition is inside the loop.
while(true) {
//Provide options to the user.
System.out.println("\tMenu");
System.out.println("\t-------------------------------------------------");
System.out.println("1. Add a list of Students and save to File");
System.out.println("2. Loading list of Students from a File");
System.out.println("3. Display the list of Students descending by Name");
System.out.println("4. Display the list of Students descending by Mark");
System.out.println("x. Exit");
System.out.print("\tYour choice:");
String input = br.readLine().trim();
//If user input exit, break the loop.
if(input.equalsIgnoreCase("x"))
break;
else {
//For other options, call the appropriate function.
switch(input) {
case "1":
addRecords();
break;
case "2":
loadRecords();
break;
case "3":
displayByName();
break;
case "4":
displayByMark();
break;
default:
//Print a message if an invalid option is entered.
System.out.println("Invalid choice. Please try again.");
break;
}
}
}
}
//Comparators for sorting the array list.
static class SortHandlerByName implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return (a.GetName().compareTo(b.GetName()));
}
}
static class SortHandlerByMark implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
if(a.GetMark() == b.GetMark())
return 0;
else if(a.GetMark() > b.GetMark())
return -1;
else
return 1;
}
}
}
The screenshots of the code and output are provided below.