Question

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 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.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;

public class Student {
   private String name;
   private int age;
   private double gpa;

   public Student(String name, int age, double gpa) {
       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 + " " + age + " " + gpa;
   }
}

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

public class Students {
   private ArrayList<Student> students;

   public Students() {
       students = new ArrayList<Student>();
   }

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

   public void read() {
    File file = new File("Students.txt");
       try {
           Scanner sc = new Scanner(file);
           while (sc.hasNextLine()) {
               String name = sc.next();
               int age = sc.nextInt();
               double gpa = sc.nextDouble();
               add(new Student(name, age, gpa));
           }
           sc.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
   }

   @Override
   public String toString() {
       String str = "";
       for (Student student : students) {
           str += student.toString() + "\r\n";
       }
       return str;
   }

   public Student bestStudent() {
       double bestGPA = 0;
       int index = 0;
       for (int i = 0; i < students.size(); i++) {
           if (bestGPA < students.get(i).getGpa()) {
               bestGPA = students.get(i).getGpa();
               index = i;
           }
       }
       return students.get(index);
   }

   public double averageGPA() {
       double sum = 0;
       for (Student student : students) {
           sum += student.getGpa();
       }
       return sum / students.size();
   }

   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;
   }

   public int countAboveGpa(double avgGPA) {
       int count = 0;
       for (int i = 0; i < students.size(); ++i) {
           if (students.get(i).getGpa() > avgGPA)
               count++;
       }
       return count;
   }

   public int countBelowGpa(double avgGPA) {
       int count = 0;
       for (int i = 0; i < students.size(); ++i) {
           if (students.get(i).getGpa() < avgGPA)
               count++;
       }
       return count;
   }

   public Student getYoungestBelowGpa(double avgGPA) {
       Student s = students.get(0);

       for (int i = 1; i < students.size(); ++i) {
           if (students.get(i).getGpa() < avgGPA && students.get(i).getAge() < s.getAge())
               s = students.get(i);
       }

       return s;
   }

   public double getAverageAgeBelowAverageGpa(double avgGPA) {
       double sumAge = 0;
       for (int i = 1; i < students.size(); ++i) {
           if (students.get(i).getGpa() < avgGPA)
               sumAge += students.get(i).getAge();
       }
       return sumAge / students.size();
   }
  

}

=========================================================
public class Tester {
   public static void main(String[] args) throws FileNotFoundException {
         
      
       Students std = new Students();
       std.read();
       System.out.println("1) All Students: ");
       System.out.println(std);

       System.out.print("\n2). Student with best GPA is: ");
       System.out.println(std.bestStudent());

       double avgGPA = std.averageGPA();
       System.out.printf("\n3). Average GPA is: %.2f\n", std.averageGPA());

       int aboveGpa = std.countAboveGpa(avgGPA);
       int belowGpa = std.countBelowGpa(avgGPA);

       System.out.println("\n4). Number of students with above average GPA: " + aboveGpa
               + "\n Number of students with below average GPA: " + belowGpa);

       System.out.printf("\n5). All Students above the average of %.2f\n", avgGPA);
       System.out.println(std.aboveAverage(avgGPA).toString());

       System.out.println("\n6). Youngest Student who has a below average GPA: " + std.getYoungestBelowGpa(avgGPA));

       System.out.printf("\n7). The average age of the students with below average GPA: %.2f",
               std.getAverageAgeBelowAverageGpa(avgGPA));

       PrintWriter writer1 = null;
       writer1 = new PrintWriter(new File("output.txt"));
       writer1.write("1) All Students: ");
       writer1.write(std.toString());

       writer1.write("\r\n2). Student with best GPA is: ");
       writer1.write(std.bestStudent().toString());

       writer1.write("\r\n\r\n3). Average GPA is: " + std.averageGPA());

       writer1.write("\r\n\r\n4). Number of students with above average GPA: " + aboveGpa
               + "\r\n Number of students with below average GPA: " + belowGpa);

       writer1.write("\r\n\r\n5). All Students above the average of " + avgGPA);
       writer1.write(std.aboveAverage(avgGPA).toString());

       writer1.write("\r\n\r\n6). Youngest Student who has a below average GPA: " + std.getYoungestBelowGpa(avgGPA));

       writer1.write("\r\n\r\n7). The average age of the students with below average GPA: "
               + std.getAverageAgeBelowAverageGpa(avgGPA));

       writer1.close();

   }

}

==========================================================================
See Output , Make Sure, you have a file with name Students.txt

Thanks, PLEASE COMMENT if there is any concern.

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...
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 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...

  • 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)...

  • 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 programming language Please write code for the 6 methods below: Assume that Student class...

    In Java programming language Please write code for the 6 methods below: Assume that Student class has name, age, gpa, and major, constructor to initialize all data, method toString() to return string reresentation of student objects, getter methods to get age, major, and gpa, setter method to set age to given input, and method isHonors that returns boolean value true for honors students and false otherwise. 1) Write a method that accepts an array of student objects, and n, the...

  • 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...

  • 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...

  • Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written...

    Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written to a file. Each line of the input file will contain the student name (a single String with no spaces), the number of semester hours earned (an integer), the total quality points earned (a double). The following shows part of a typical...

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