Question

In: Computer Science

The program reads a text file with student records (first name, last name and grade on...

  • The program reads a text file with student records (first name, last name and grade on each line) and determines their type (excellent or ok). <--- Completed
  • Need help on this
  • Then it prompts the user to enter a command, executes the command and loops. The commands are the following:
    • "all" - prints all student records (first name, last name, grade, type).
    • "excellent" - prints students with grade > 89.
    • "ok" - prints students with grade <= 89.
    • "end" - exits the loop the terminates the program.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Students
{
public static void main (String[] args) throws IOException
{ String first_name, last_name;
int grade, count=0;
Scanner fileInput = new Scanner(new File("students.txt"));
//Object st;
ArrayList<Student> st = new ArrayList<Student>();
while (fileInput.hasNext())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();

if (grade>89)
st.add(new Excellent(first_name, last_name, grade));
else
st.add(new Ok(first_name, last_name, grade));

count++;
}
  
for (int i=0; i<st.size(); i++)
{
if (st.get(i) instanceof Excellent)
st.get(i).info();
else
st.get(i).info();
}   
  
System.out.println("There are " + count + " students");
  
}
}

public class Ok implements Student
{
private String fname, lname;
private int grade;
  
public Ok(String fname, String lname, int grade)
{
this.fname = fname;
this.lname = lname;
this.grade = grade;
}

public void info()
{
System.out.println(fname + " " + lname + " "+ grade + "\t" + "ok");
}
}

public class Excellent implements Student
{
private String fname, lname;
private int grade;

public Excellent(String fname, String lname, int grade)
{
this.fname = fname;
this.lname = lname;
this.grade = grade;
}

public void info()
{
System.out.println(fname + " " + lname + " "+ grade + "\t" + "excellent");
}
}


public interface Student
{
void info();
}

Solutions

Expert Solution

Thanks for the question.

Below is the code you will be needing  Let me know if you have any doubts or if you need anything to change.

I have assumed the text file is a comma separated file, incase it is space separated file replace the below line as 

String[] tokens = line.split(",");

to

String[] tokens = line.split("\\s+");


Thank You !!

===========================================================================


public class Student {

    private String firstName;
    private String lastName;
    private int grade;

    public Student(String firstName, String lastName, int grade) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.grade = grade;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Name: " + firstName + " " + lastName + ", Grade: " + grade;
    }
}

=============================================================

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Students {

    public static void main(String[] args) {

        String fileName = "students.txt";
        ArrayList<Student> records = null;
        try {
            records = getDataFromFile(fileName);
        } catch (FileNotFoundException e) {
            System.out.println("Unable to read data from file: " + fileName);
            System.exit(1);
        }

        String input;
        Scanner sc = new Scanner(System.in);
        System.out.println("\"all\" - prints all students");
        System.out.println("\"excellent\" - prints all students grade>89");
        System.out.println("\"ok\" - prints all students grade<=89");
        System.out.println("\"end\" - exit program");
        while (true) {

            System.out.println("Enter your command here > ");
            input = sc.nextLine();
            if (input.equals("all")) {
                for (Student student : records) System.out.println(student);
            }else if(input.equals("excellent")){
                for(Student student:records){
                    if(student.getGrade()>89) System.out.println(student);
                }
            }else if(input.equals("ok")){
                for(Student student:records){
                    if(student.getGrade()<=89) System.out.println(student);
                }
            }else if(input.equals("end"))break;
            else System.out.println("Invalid command please try again.");

        }


    }

    private static ArrayList<Student> getDataFromFile(String fileName) throws FileNotFoundException {

        Scanner fileScanner = new Scanner(new File(fileName));
        ArrayList<Student> students = new ArrayList<Student>();

        while (fileScanner.hasNext()) {
            String line = fileScanner.nextLine();
            //System.out.println(line);
            // assummed the data a separated by comma in the file
            String[] tokens = line.split(",");
            int grade = Integer.parseInt(tokens[2].trim());

            students.add(new Student(tokens[0].trim(), tokens[1].trim(), grade));

        }
        fileScanner.close();
        return students;

    }
}


Related Solutions

Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
Write a program, which reads a list of student records from a file in batch mode....
Write a program, which reads a list of student records from a file in batch mode. Each student record comprises a roll number and student name, and the student records are separated by commas. An example data in the file is given below. · SP18-BCS-050 (Ali Hussan Butt), SP19-BCS-154 (Huma Khalid), FA19-BSE-111 (Muhammad Asim Ali), SP20-BSE-090 (Muhammad Wajid), SP17-BCS-014 (Adil Jameel) The program should store students roll numbers and names separately in 2 parallel arrays named names and rolls, i.e....
C++ Write a program that prompts for a file name and then reads the file to...
C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on. These are a few of the...
A.Write a program that prompts for and reads the user’s first and last name (separately).Then print...
A.Write a program that prompts for and reads the user’s first and last name (separately).Then print the initials with the capital letters. (Note that we do not expect that inputs from users are case-sensitive. For example, if the user’s input of the first name is robert and of the last name is SMITH, you should print R.S.) B.Write a program that creates and prints a random phone number of the form XXX-XXX-XXXX. Include the dashed in the output. Do not...
Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
Write a program that reads a file called document.txt which is a text file containing an...
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces...
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces another text file in Which blank lines are removed, multiple blanks are replaced with a single blank, and no lines are longer than some given length (let say 80). Put as many words as possible on the same line (as close as possible to 80 characters). You will have to break some lines of the given file, but do not break any words or...
Write a simple phonebook using c++ that read text file name list.txt and has:  first name, last...
Write a simple phonebook using c++ that read text file name list.txt and has:  first name, last name, and phone number as the example: MIKEL BUETTNER 3545044 ENOCH BUGG 2856220 BRENDON LAVALLEY 433312 QUINTIN CREEK 5200413 JAMISON MILLETT 6243458 FLORENCIO PUMPHREY 3296862 DARRICK FREGOSO 6868442 TOBIAS GLASSMAN 6040564 and then ask the user to add a new contact first name, last name, and phone number and same the information into a file. Use array and pointer
You are given a text file containing a short text. Write a program that 1. Reads...
You are given a text file containing a short text. Write a program that 1. Reads a given text file : shortText.txt 2. Display the text as it is 3. Prints the number of lines 4. Prints the occurences of each letter that appears in the text. [uppercase and lowercase letter is treated the same]. 5. Prints the total number of special characters appear in the text. 6. Thedisplayofstep3,4and5aboveshouldbesaveinanoutputfile:occurencesText.txt write it in C++ programing Language
Write the programs in JavaScript: Write a program that reads a text file and outputs the...
Write the programs in JavaScript: Write a program that reads a text file and outputs the text file with line numbers at the beginning of each line.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT