Question

In: Computer Science

CODE IN JAVA Create a class Student includes name, age, mark and necessary methods. Using FileWriter,...

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

-------------------------------------------------

  1. Add a list of Students and save to File
  2. Loading list of Students from a File
  3. Display the list of Students descending by Name
  4. Display the list of Students descending by Mark
  5. Exit

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

Solutions

Expert Solution

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.


Related Solutions

Code in Java 1. Create a class Flower with data: Name, Price, Color and properly methods....
Code in Java 1. Create a class Flower with data: Name, Price, Color and properly methods. 2. Create another class named ListFlower. This class manages a collection of Flower (may be LinkedList) named a. Implementing some methods for ListFlower: Add: add new item of Flower to a Display: display all items of a sort(): sort as descending by Price and display all items of a search(Flower f): check and return whether f is exists in a or not. delete(int pos):...
Create java Class with name Conversion. Instructions for Conversion class: The Conversion class will contain methods...
Create java Class with name Conversion. Instructions for Conversion class: The Conversion class will contain methods designed to perform simple conversions. Specifically, you will be writing methods to convert temperature between Fahrenheit and Celsius and length between meters and inches and practicing overloading methods. See the API document for the Conversion class for a list of the methods you will write. Also, because all of the methods of the Conversion class will be static, you should ensure that it is...
Please Code Using Java Create a class called SoccerPlayer Create 4 private attributes: First Name, Last...
Please Code Using Java Create a class called SoccerPlayer Create 4 private attributes: First Name, Last Name, Games, and Goals Have two constructors Constructor 1 – default constructor; all values to "NONE" or zero Constructor 2 – accepts input of first name, last name, games and goals. Create get and set methods for each of the four attributes Create a method the returns a double that calculates the average goals per game This method checks for zero games played: If...
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name...
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its value. Write a test app names EmployeeTest that demonstrates class EMLOYEE’s capabilities. Create two EMPLOYEE objects and display each object’s yearly...
java code Add the following methods to the LinkedQueue class, and create a test driver for...
java code Add the following methods to the LinkedQueue class, and create a test driver for each to show that they work correctly. In order to practice your linked list cod- ing skills, code each of these methods by accessing the internal variables of the LinkedQueue, not by calling the previously de?ined public methods of the class. String toString() creates and returns a string that correctly represents the current queue. Such a method could prove useful for testing and debugging...
In Java, using the code provided for Class Candle, create a child class that meets the...
In Java, using the code provided for Class Candle, create a child class that meets the following requirements. Also compile and run and show output ------------------------------------------------------------------------ 1. The child class will be named  ScentedCandle 2. The data field for the ScentedCandle class is:    scent 3. It will also have getter and setter methods 4. You will override the parent's setHeight( ) method to set the price of a ScentedCandle object at $3 per inch (Hint:   price = height * PER_INCH) CODE...
Java Create a class named Billing that includes three overloaded computeBill() methods for a photo book...
Java Create a class named Billing that includes three overloaded computeBill() methods for a photo book store. main() main() will ask the user for input and then call functions to do calculations. The calculations will be returned to main() where they will be printed out. First function Create a function named computeBill that receives on parameter. It receives the price of an item. It will then add 8.25% sales tax to this and return the total due back to main()....
IN JAVA PLEASE Create a class called Child with an instance data values: name and age....
IN JAVA PLEASE Create a class called Child with an instance data values: name and age. a. Define a constructor to accept and initialize instance data b. include setter and getter methods for instance data c. include a toString method that returns a one line description of the child
JAVA PROGRAMMING Part 1 Create a class Student, with attributes id, first name, last name. (All...
JAVA PROGRAMMING Part 1 Create a class Student, with attributes id, first name, last name. (All the attributes must be String) Create a constructor that accepts first name and last name to create a student object. Create appropriate getters and setters Create another class StudentOperationClient, that contains a main program. This is the place where the student objects are created and other activities are performed. In the main program, create student objects, with the following first and last names. Chris...
Code in Java Write a Student class which has two instance variables, ID and name. This...
Code in Java Write a Student class which has two instance variables, ID and name. This class should have a two-parameter constructor that will set the value of ID and name variables. Write setters and getters for both instance variables. The setter for ID should check if the length of ID lies between 6 to 8 and setter for name should check that the length of name should lie between 0 to 20. If the value could not be set,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT