Question

In Java(using BlueJ) Purpose Purpose is to practice using file input and output, and array list of objects. Also, this lab specification tells you only what to do, you now have more responsibility to...

In Java(using BlueJ)

Purpose

Purpose is to practice using file input and output, and array list of objects. Also, this lab specification tells you only what to do, you now have more responsibility to design how to do it.

Problem description

You are given a text file called 'Students.txt' that contains information on many students. Your program reads the file, creating many Student objects, all of which will be stored into an array list of Student objects, in the Students class. The Tester class controls everything, calling many Students class methods to produce lots of different outputs. The program must write the output to an output file and to the Terminal Window.

File and class specifications

Students.txt file format

Information for each student is stored in the file as 3 lines of text:

name
age
GPA

e.g. the following shows data for two students:

Name0
22
1.2
Name1
22
2.71

Student class

The Student class has instance variables and methods to represent one single student.

Your Student class must have exactly and only the following instance variables:

private String name;
private int age;
private double gpa;

Design appropriate constructors and other methods for your Student class, including:

+ toString() – returns a String containing the 3 instance variables e.g.

Name0       22    1.2

Students class

Very importantly, the Students class is used to store and process many Student objects. It will have an instance variable to store many Student objects. Methods intended to process many Student objects belong in this Students class.

Your Students class must have exactly and only the following instance variable:

private ArrayList students;

students here is an array list of Student objects, in which all of the Student objects are stored.

Students must have appropriate constructors and methods, including the following:

+ readFile() – opens the data file, reads the data, creates Student objects, and adds them to the students array list

+ toString() – returns a String containing a line of information for each Student in the students array list. Must call the Student class’s toString() as it builds the big String. Example of output:

Name0       22    1.2
Name1       22    2.71
. . .

Many other methods for processing a Students object. Most of the code you write will be in this class.

Reading the data file

Your program will use the Scanner class to read from the data file, as demonstrated during the Files lecture.

Writing the output file

Your program must use the PrintWriter class to save all its output to the output.txt file, as demonstrated during the Files lecture. It will also send the same output to the BlueJ Terminal Window, as usual.

Tester class

The Tester class controls everything.  Tester does not have any instance variables. You have to write the Tester class.

Tester contains only a main() method, which first creates a single Students object and a PrintWriter object. The Students object then calls a separate Students method to do each of the different tasks indicated below. You must design appropriate parameters and return values, in particular so that all program output to Terminal Window and output.txt is done from main(). In pseudocode:

+ main()               

create an empty Students object

create a new PrintWriter object to create the ‘output.txt’ output file

  1. read data file into Students
  2. print all Student objects from Students (must call the Students class toString() method to do this)
  3. print the Student with the best GPA
  4. calculate and print the average GPA
  5. calculate and print the number of students with above average GPA and the number of students with below average GPA
  6. print all the Student objects with above average GPA
  7. print the youngest Student who has a below average GPA
  8. calculate and print (to 2 decimal places) the average age of the students with below average GPA

Hints

  • the Students.txt data file is available in Canvas, ‘Exceptions’, Example programs. You must copy it into your BlueJ project folder
  • you will need to add throws IOException to your Tester class main() method header and the Students class readFile() method header. For example, in Tester:

public static void main(String args[]) throws IOException

This prevents a file handling syntax error: “unreported exception java.io.IOException; must be caught or declared to be thrown”

  • (you may want to review array lists from the ‘Arrays and array lists’ week)
  • it is important in this lab always to keep in mind that each element in the Students class array list is itself an entire Student object...
  • it is essential that you draw pictures of the objects involved in your program, so that you are always aware of the data type you are working with
  • the different actions above will each be implemented as a separate public Students method, called from main() by the Students object, using appropriate parameters and return types
  • (by the way, there is no inheritance in this lab. So no standard formatting for inheritance in the toString() methods)

Syntax for processing an array list of objects

  • the syntax for processing an array list of Student objects is exactly as you would expect. For example, here’s a method that prints all the Students with GPAs above the average
    • first, the method call in main(). Since we must do all printing from main(), we design aboveAverage() to return a new Students object:

System.out.printf("\nGPAs above the average of %.2f\n", gpa);
ot.printf("\nGPAs above the average of %.2f\n", gpa);
System.out.println(students.aboveAverage(gpa).toString());
ot.println(students.aboveAverage(gpa).toString());

  • since aboveAverage() deals with many students, it would be part of the Students It creates a new Students object in which to return many Studentobjects e.g.

public Students aboveAverage(double avgGPA)
{
    Students aboveAverage = new Students();

    for (int i = 0; i < students.size(); ++i) {
        if (students.get(i).getGPA() > avgGPA)
aboveAverage.add(students.get(i));
    }
    return aboveAverage;
}

  • see that it calls a method getGPA(), that must directly return the GPA of a student. So getGPA() would be part of the Student class:

public double getGPA()
{
    return gpa;
}

  • it also calls a method add(), that takes a Student object and adds it to a Students So add() would be part of the Students class:

public void add(Student s)
{
    students.add(s);
}

Designing method return types

  • the natural unit of an object-oriented program is an object. So methods returning results tend to return entire objects. Some hypothetical examples to illustrate this:
  • g. bestStudent() returns a single student, so would return a Student object. Method header would be something like:

public Student bestStudent(~~~~~~)

  • g. aboveAverage() returns many students, so would return a Students object. Method header would be something like:

public Students aboveAverage(~~~~~~)

  • (of course methods can also return non-object data types if that is appropriate) e.g. averageGPA() returns the average GPA, so method header would be something like:

public double averageGPA()

Extra credit

Many students will start this lab late, run out of time to finish everything properly, and not score well.

So extra credit is available to fix this problem. 20% extra credit will be added to your score, if you submit your final version by the end of the Thursdaybefore the Sunday deadline. (See Canvas for due date. And I will still grade all the labs together on the Monday, as usual.)

Required

  • your program must work for a file containing any number of students
  • you are required this time to use PrintWriter to create your txt output file. Cannot just save the Terminal Window output as usual
  • your program must clearly label each part of the output e.g. "2. All students:”, “3. Student with best GPA is:", "4. Average GPA is: ", "5. Above / below average GPA:", etc, etc
  • use good programming practices regarding encapsulation of class instance variables i.e. all must be declared private as shown above
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

class Student{
   DecimalFormat df2 = new DecimalFormat("#.##");
   private String name;
   private int age;
   private double gpa;
   ArrayList<Student> students = new ArrayList<Student>();
  
   public ArrayList<Student> getStudents() {
       return students;
   }
   public Student() {
   }
   public Student(String name, int age, double gpa) {
       super();
       this.name = name;
       this.age = age;
       this.gpa = gpa;
   }
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
   public double getGpa() {
       return gpa;
   }
   public void setGpa(double gpa) {
       this.gpa = gpa;
   }
   @Override
   public String toString() {
       return "name=" + name + ", age=" + age + ", gpa=" + gpa ;
   }
   public void add(Student s)
   {
   students.add(s);
   }
   //print the Student with the best GPA
   public Student bestGPA(){
       double maxGPA = students.get(0).getGpa();
       int index = 0;
       for(int i=1;i<students.size();i++){
           if(students.get(i).getGpa()>maxGPA)   {
               maxGPA = students.get(i).getGpa();
               index = i;
           }
       }
       return students.get(index);
   }
   //calculate and print the average GPA
   public double averageGPA(){
       double sum = 0;
       for(int i=0;i<students.size();i++){
           sum += students.get(i).getGpa();
       }
       return Double.parseDouble(df2.format(sum/students.size()));
   }
   //calculate and print the number of students with above average GPA and the number of students with below average GPA
   public int aboveAverageGPAcount(){
       double average = averageGPA();
       int count = 0;
       for(int i=0;i<students.size();i++){
           if(students.get(i).getGpa()>average) count++;
       }
       return count;
   }
   public int belowAverageGPAcount(){
       double average = averageGPA();
       int count = 0;
       for(int i=0;i<students.size();i++){
           if(students.get(i).getGpa()<average) count++;
       }
       return count;
   }
   //print all the Student objects with above average GPA
   public ArrayList<Student> aboveAverageGPAstudents(){
       ArrayList<Student> aboveAverageStudents = new ArrayList<Student>();
       double average = averageGPA();
       for(int i=0;i<students.size();i++){
           if(students.get(i).getGpa()>average) aboveAverageStudents.add(students.get(i));
       }
       return aboveAverageStudents;
   }
   //print the youngest Student who has a below average GPA
   public Student youngStudentBelowAverageGPA(){
       int age = students.get(0).getAge();
       int index = 0;
       double average = averageGPA();
       for(int i=1;i<students.size();i++){
           if(students.get(i).getGpa()<average){
               if(students.get(i).getAge()<age){
                   age = students.get(i).getAge();
                   index = i;
               }
           }
       }
       return students.get(index);
   }
   //calculate and print (to 2 decimal places) the average age of the students with below average GPA
   public double averageAgeBelowAverageGPA(){
       double ageSum = 0;
       int count = 0;
       double average = averageGPA();
       for(int i=0;i<students.size();i++){
           if(students.get(i).getGpa()<average){
               ageSum += students.get(i).getAge();
               count++;
           }
       }
       return Double.parseDouble(df2.format(ageSum/count));
   }
}
public class StudentTest {
   public static void main(String[] args) {
       /*read data file into Students
       print all Student objects from Students (must call the Students class toString() method to do this)
       print the Student with the best GPA
       calculate and print the average GPA
       calculate and print the number of students with above average GPA and the number of students with below average GPA
       print all the Student objects with above average GPA
       print the youngest Student who has a below average GPA
       calculate and print (to 2 decimal places) the average age of the students with below average GPA*/
      
       String name;
       int age;
       double gpa;
       Student student;
       Student studentobj = new Student();
       try {
       File file = new File("students.txt");
       FileWriter fw=new FileWriter("studentsoutput.txt");
     
   Scanner sc = new Scanner(file);
   while (sc.hasNextLine()) {
   name = sc.nextLine();
   age = Integer.parseInt(sc.nextLine());
   gpa = Double.parseDouble(sc.nextLine());
   student = new Student(name,age,gpa);
   studentobj.add(student);
   fw.write(student.toString());
   fw.write("\r\n");
   System.out.println(student.toString());
   }
  
   System.out.println("\nStudent with the best GPA -> "+studentobj.bestGPA());
   fw.write("Student with the best GPA -> "+studentobj.bestGPA()+"\r\n\n");
  
   System.out.println("\nAverage GPA of all Students -> "+studentobj.averageGPA());
   fw.write("Average GPA of all Students -> "+studentobj.averageGPA()+"\r\n\n");
  
   System.out.println("\nnumber of students with above average GPA -> "+studentobj.aboveAverageGPAcount());
   fw.write("number of students with above average GPA -> "+studentobj.aboveAverageGPAcount()+"\r\n\n");
  
   System.out.println("\nnumber of students with blow average GPA -> "+studentobj.belowAverageGPAcount());
   fw.write("number of students with blow average GPA -> "+studentobj.belowAverageGPAcount()+"\r\n\n");
  
   //Student objects with above average GPA
   System.out.println("\nStudent objects with above average GPA -> ");
   ArrayList<Student> studentsAboveAverage = studentobj.aboveAverageGPAstudents();
   for(Student studentaboveaverage:studentsAboveAverage){
       System.out.println(studentaboveaverage);
       fw.write(studentaboveaverage+"\r\n");
   }
  
  
   System.out.println("\nyoungest Student who has a below average GPA -> "+studentobj.youngStudentBelowAverageGPA());
   fw.write("youngest Student who has a below average GPA -> "+studentobj.youngStudentBelowAverageGPA()+"\r\n\n");
  
     
   System.out.println("\naverage age of the students with below average GPA -> "+studentobj.averageAgeBelowAverageGPA());
   fw.write("average age of the students with below average GPA -> "+studentobj.averageAgeBelowAverageGPA()+"\r\n\n");
  
   sc.close();
   fw.close();   
   System.out.println("\n***Data has written successfully to the file***");
   }
   catch (FileNotFoundException e) {
   e.printStackTrace();
   }
       catch (Exception e) {
   e.printStackTrace();
   }
   }
}

Name0, age-22, gpa-1.2 name= name-Namel, a name-Name2, age-21, gpa-1.2 name-Name3, age-19, gpa 3.01 name-Name4, age-23, gpa-2

students.txt - Notepad File Edit Format View Help ame0 Name1 3.71 Name2 21 Name3 19 3.01 Name4 23 2.2 Name5 21 1.71

studentsoutput.txt - Not File Edit Format View Help ame Name, age-22, gpa 1.2 name Name1, age-22, gpa 3.71 name Name2, age-21

Student studentobj- new Student ); try t i: i ijis: : new ijix:(students.txt FileWriter fysnew FileWriter(トtudentsoutput.t

Add a comment
Know the answer?
Add Answer to:
In Java(using BlueJ) Purpose Purpose is to practice using file input and output, and array list of objects. Also, this lab specification tells you only what to do, you now have more responsibility to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java(using BlueJ) Purpose Purpose is to practice using file input and output, and array list...

    In Java(using BlueJ) Purpose Purpose is to practice using file input and output, and array list of objects. Also, this lab specification tells you only what to do, you now have more responsibility to design how to do it. Problem description You are given a text file called 'Students.txt' that contains information on many students. Your program reads the file, creating many Student objects, all of which will be stored into an array list of Student objects, in the Students...

  • java This lab is intended to give you practice creating a class with a constructor method,...

    java This lab is intended to give you practice creating a class with a constructor method, accessor methods, mutator methods, equals method , toString method and a equals method. In this lab you need to create two separate classes, one Student class and other Lab10 class. You need to define your instance variables, accessor methods, mutator methods, constructor, toString method and equals method in Student class. You need to create objects in Lab10 class which will have your main method...

  • I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student...

    I need code in java The Student class: CODE IN JAVA: Student.java file: public class Student {    private String name;    private double gpa;    private int idNumber;    public Student() {        this.name = "";        this.gpa = 0;        this.idNumber = 0;    }    public Student(String name, double gpa, int idNumber) {        this.name = name;        this.gpa = gpa;        this.idNumber = idNumber;    }    public Student(Student s)...

  • You are given a specification for some Java classes as follows.   A building has a number...

    You are given a specification for some Java classes as follows.   A building has a number of floors, and a number of windows. A house is a building. A garage is a building. (This isn’t Florida-like … it’s a detached garage.) A room has a length, width, a floor covering, and a number of closets. You can never create an instance of a building, but every object that is a building must have a method that calculates the floor space,...

  • Set-Up · Create a new project in your Eclipse workspace named: Lab13 · In the src...

    Set-Up · Create a new project in your Eclipse workspace named: Lab13 · In the src folder, create a package named: edu.ilstu · Import the following files from T:\it168\Labs\lab13. Note that the .txt file must be in the top level of your project, not inside your src folder. o Student.java o StudentList.java o students.txt Carefully examine the Student.java and StudentList.java files. You are going to complete the StudentList class (updating all necessary Javadoc comments), following the instruction in the code....

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

  • Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the...

    Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the concept of a college course, assuming that a course has following attributers: code (for instance COSC1337), a description, and a number of credits (for instance 3). Include a constructor, the accessors, mutators and methods ‘toString’, ‘equals’, and ‘finalize’. Write a client class to test the behavior of the class and its methods. The outline of the class is given as follows: public class Course...

  • Here is a sample run of the tester program: Make sure your program follows the Java...

    Here is a sample run of the tester program: Make sure your program follows the Java Coding Guidelines. Consider the following class: /** * A store superclass with a Name and Sales Tax Rate */ public class Store {      public final double SALES_TAX_RATE = 0.06;      private String name;           /**      * Constructor to create a new store      * @param newName      */      public Store(String newName)      {           name = newName;      }     ...

  • // Client application class and service class Create a NetBeans project named StudentClient following the instructions...

    // Client application class and service class Create a NetBeans project named StudentClient following the instructions provided in the Starting a NetBeans Project instructions in the Programming Exercises/Projects Menu on Blackboard. Add a class named Student to the StudentClient project following the instructions provided in the Starting a NetBeans Project instructions in the Programming Exercises/Projects Menu on Blackboard. After you have created your NetBeans Project your application class StudentC lient should contain the following executable code: package studentclient; public class...

  • In Java, Implement a class MyArray as defined below, to store an array of integers (int)....

    In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion. Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT