JAVA Programming please check if my code is correct and if it is doing what it i
ID: 3730799 • Letter: J
Question
JAVA Programming please check if my code is correct and if it is doing what it is supposed to do.
I wrote a program the best i could to answer the prompt. i was not given an expoected output.
Assignment 6 Prompt
This assignment is built using the code from Assignment 5.
In this assignment create a separate serialized file using ObjectOutputStream for each student.
File should contain student's score and statistics for entire class.
Using debug mode (with Debug flag) print the contents of the serialized file.
Create and implement an interface to:
Print student statistics.
Print scores for a given student id.
implement the Debug flag globally
Use an abstract class to implement all the methods declared in an interface.
Checklist for lab 6
1. Add “implements serializable” to student class and statistics class
2. Create studentReport class in the model package
3. When you write the print method for studentReport call the print method from statistics and student class
4. Create an array of student report objects for serialization in main
5. Writing/serializing student report objects to disk
6. Create a new package called adapter and put in public interface printable
7. Write public class print implements printable
8. Load the text file
9. Compute the statistics
10. Create an array of student grades
11. Serialize
Tips: --
package model;
public class Student implements Serializable {
}
package model;
public class Statistics implements Serializable{
}
package model;
public class StudentReport implements Serializable{
//we will serialize instances of Student Report.
private Student x; //for one student
private Statistics y; //for entire class.
//no default constructor as it will not make sense.
StudentReport(Student x, Statistics y)
{
this.x = x;
this.y = y;
}
//getter and setters
//print()
}
Student and Statistics are free of any static variables or methods - cannot be serialized.
//main
//stu is from student array - read from text file.
//stat object is from Statistics class.
public class Driver {
//run lab5 so data in student [] is loaded and statistics are computed.
//How to write one StudentReport to disk using serialization?
//StudentReport a1 = new StudentReport(stu, stat);
//FileIO f = new FileIO();
//f.writetodisk(a1);
//How to write n objects of StudentReport to disk using serialization?
//Assumption - u already have an array of students from lab5 from readdata()
//Build an array of StudentReport
StudentReport arr[] = new StudentReport[40];
//stu[] array is populated using lab5 read method (that reads from the file).
//building studentreport array
for(int i=0;i<40;i++)
{
if(stu[i]!=null) //avoiding NPE.
arr[i] = new StudentReport(stu[i], stat);
}
for(int i=0;i<40;i++)
{
if(arr[i]!=null)
{
StudentReport temp = arr[i];
Student temp2 = temp.getStudent();
int sid = temp2.getid();
String fname = sid + ".ser"; //this may not work???
f.writetodisk(arr[i],fname);
//f.writetodisk(arr[i],(arr[i].getStudent().getid().toString())+".ser"));
}
}
}
import java.io.*;
package util;
public class FileIO { //or Util or whatever name of class you are using in util package.
public void writetodisk(StudentReport a1, String fname)
{
try {
FileOutputStream p = new FileOutputStream(fname);
ObjectOutputStream p1 = new ObjectOutputStream(p);
p1.writeObject(a1);
}
catch(Exception e)
{
//exception message
}
}
public StudentReport readfromdisk(String fname)
{
StudentReport a= null;
try {
FileInputStream p = new FileInputStream(fname);
ObjectInputStream p1 = new ObjectInputStream(p);
a = (StudentReport )p1.readObject();
}
catch(Exception e)
{
//exception message
}
return a;
}
}
Using debug mode (with Debug flag) print the contents of the serialized file.
Create and implement an interface to:
..Print student statistics.
..Print scores for a given student id.
..implement the Debug flag globally
//....Use an abstract class to implement all the methods declared in an interface.
Interface -
face - input/output
inter - communication
Adding a face to software for communication.
public interface Faceable {
public final boolean DEBUG=false; //global variables.
public void smile();
}
public class Human implements Faceable {
//enforces a contract to Human to implement smile() method.
//if Human does not implement methods in Faceable interface - then compiler error.
public void smile() {
System.out.println("..smile from human");
}
}
public class Ape implements Faceable {
public void smile() {
System.out.println("..smile from ape");
}
}
Human a1 = new Human();
a1.smile();
Ape a2 = new Ape();
a2.smile();
Faceable a3;
a3 = a1;
a3.smile();
a3 = a2;
a3.smile();
Making a face for software -
Using debug mode (with Debug flag) print the contents of the serialized file.
Create and implement an interface to:
..Print student statistics.
..Print scores for a given student id.
..implement the Debug flag globally
package adapter;
public interface Printable{
public final boolean DEBUG = false;
public void getStats(); //prints students statistics.
public void printstudentscores(int id);
}
import model.*;
import util.*;
package adapter;
public class Print implements Printable {
//use debug flag for printing. if debug = true then print other no printing.
public void getStats() {
//print stats from any object - read one object from disk and print stats.
}
public void printstudentscores(int id) {
//use the serialized life so your life is easy.
//pl. don't use search in studentreport array. long way. no good.
}
}
//how to use an interface in main()
Printable p1 = new Print();
p1.getStats();
p1.printstudentscores(1234);
p1.printstudentscores(9111); //invalid student id shld print a friendly message - no such student.
____________________________________________________________________________________________________
Completed code
import fileIO.Util;
import model.Statistics;
import model.Student;
import model.StudentReport;
import adapter.Print;
public class Driver {
/**
* Create Object of StudentReport class and Process the Student report.
*/
public static void main(String[] args) {
StudentReport report = new StudentReport();
report.process();
}
}
------------------------------------------------------------------------------------------------------
package model;
import adapter.Print;
import fileIO.Util;
public class StudentReport {
/**
* Function to process the Student Reports.
*
* 1. Read the Data from input file Scores.txt and load into an array of students.
* 2. Serialize the students to a file
* 3. Use Print class functions to display entire student report.
* 4. use randomly picked students and print their individual report.
*/
public void process()
{
// Load File
Student students[] = Util.readFile("Scores.txt");
// Serialize
Util.serializeStudents(students);
// Print Statistics
Print printer = new Print();
printer.printStats();
//Randomly pick some students and print their individual reports.
System.out.println(" Randomly selected Student Reports: ");
for(int i=0; i<5; i++)
{
// Randomly student
int index = (int)(Math.random() * students.length);
System.out.println("Randomly Picked Student ID: "+ students[i].getSID());
// print the student
printer.printStudentScores(students[i].getSID());
System.out.println();
}
}
}
-------------------------------------------------------------------------------------------------------
package model;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = -123433434343L;
private int SID;
private int scores[] = new int[5];
// getter and setter functions
public int getSID() {
return this.SID;
}
// setter function
public void setSID(int id) {
this.SID = id;
}
// Get scores
public int[] getScores() {
return this.scores;
}
// set scores
public void setScores(int[] s) {
// Make deep copy
for (int i = 0; i < s.length; i++) {
this.scores[i] = s[i];
}
}
/**
* Function to determine the highest score of this student.
*
* @return highest
*/
public int getHighest() {
int highest = scores[0];
for (Integer i : scores) {
if (i > highest) {
highest = i;
}
}
return highest;
}
/**
* Function to determine the lowest score of this student.
*
* @return lowest
*/
public int getLowest() {
int lowest = scores[0];
for (Integer i : scores) {
if (i < lowest) {
lowest = i;
}
}
return lowest;
}
/**
* Function compute the average for the student
*
* @return average
*/
public double calcAverage() {
double sum = 0;
for (Integer i : scores) {
sum += i;
}
return sum / scores.length;
}
/**
* Function to determine the grade of the student.
*
* @return grade
*/
public String getGrade() {
double average = calcAverage();
if (average >= 90)
return "A";
else if (average >= 80)
return "B";
else if (average >= 70)
return "D";
else if (average >= 60)
return "D";
else
return "F";
}
// print all data of a student
public void printData() {
System.out.println("Student ID: " + SID);
String str = "Scores: ";
for (int i = 0; i < scores.length; i++) {
str += String.valueOf(scores[i]) + " ";
}
System.out.println(str);
System.out.println("Lowest Marks: " + getLowest());
System.out.println("Highest Marks: " + getHighest());
System.out.println("Average Marks: " + calcAverage());
System.out.println("Letter Grade: " + getGrade());
}
}
------------------------------------------------------------------------------------------------------
package model;
public class Statistics {
// store lowest scores of students
private int[] lowScores;
// store highest scores of students
private int[] highScores;
// store averages of students
private double[] avgScores;
// store grades of students
private String[] grades;
/**
* Function to determine the lowest scores of the students. Store them into
* an array.
*
* @param students
*/
private void calcLowest(Student[] students) {
// allocate memory
lowScores = new int[students.length];
// for each student
for (int i = 0; i < students.length; i++) {
lowScores[i] = students[i].getLowest();
}
}
/**
* Function to determine the High scores of all the students.
*
* @param students
*/
private void calcHighest(Student[] students) {
// allocate memory
highScores = new int[students.length];
// for each student
for (int i = 0; i < students.length; i++) {
highScores[i] = students[i].getHighest();
}
}
/**
* Function o compute the average and grades of all the students.
*
* @param students
*/
private void calculateAverages(Student[] students) {
// allocate memory
avgScores = new double[students.length];
grades = new String[students.length];
// for each student
for (int i = 0; i < students.length; i++) {
// compute average
avgScores[i] = students[i].calcAverage();
// compute average
grades[i] = students[i].getGrade();
}
}
// print statistics for all students and all quizzes
public void printStatistics(Student[] students) {
calcLowest(students);
calcHighest(students);
calculateAverages(students);
// Build header row
String output = "";
output += String.format("%-12s %-15s %-15s %-15s %s%n", "Student ID", "Highest Score", "Lowest Score",
"Aveage Score", "Grade");
for (int i = 0; i < students.length; i++) {
output += String.format("%-12d %-15d %-15d %-15.2f %s%n", students[i].getSID(), highScores[i], lowScores[i],
avgScores[i], grades[i]);
}
System.out.println(output);
}
}
------------------------------------------------------------------------------------------------------
package adapter;
import model.Student;
import model.Statistics;
import fileIO.Util;
public class Print implements Printable
{
/**
* Print the Student Statistics, read from the Serialized file.
*/
@Override
public void printStats() {
// Get all the Scores.
Student[] stds = Util.getStudents();
// Statistics object.
Statistics stats = new Statistics();
stats.printStatistics(stds);
}
/**
* Function to print the statistics for a Student, identified by id.
*
* @param id
*/
@Override
public void printStudentScores(int id) {
// Find Student
Student std = Util.getStudentByID(id);
if(std == null)
{
System.out.println("No Such Student exist with ID: " + id);
}
else
{
std.printData();
}
}
}
------------------------------------------------------------------------------------------------------
package adapter;
public interface Printable {
/**
* Print the Student Statistics, read from the Serialized file.
*/
public void printStats();
/**
* Function to print the statistics for a Student, identified by id.
*
* @param id
*/
public void printStudentScores(int id);
}
______________________________________________________________________________________________________
Assignment 5 prompt
Object Relationship and File IO
Write a program to perform statistical analysis of scores for a class of students.The class may have up to 40 students.
There are five quizzes during the term. Each student is identified by a four-digit student ID number.
The program is to print the student scores and calculate and print the statistics for each quiz. The output is in
the same order as the input; no sorting is needed. The input is to be read from a text file. The output from the
program should be similar to the following:
Here is some sample data (not to be used) for calculations:
Stud Q1 Q2 Q3 Q4 Q5
1234 78 83 87 91 86
2134 67 77 84 82 79
1852 77 89 93 87 71
High Score 78 89 93 91 86
Low Score 67 77 84 82 71
Average 73.4 83.0 88.2 86.6 78.6
The program should print the lowest and highest scores for each quiz.
Plan of Attack
Learning Objectives
You will apply the following topics in this assignment:
File Input operations.
Working and populating an array of objects.
Wrapper Classes.
Object Oriented Design and Programming.
Understanding Requirements
Here is a copy of actual data to be used for input.
Stud Qu1 Qu2 Qu3 Qu4 Qu5
1234 052 007 100 078 034
2134 090 036 090 077 030
3124 100 045 020 090 070
4532 011 017 081 032 077
5678 020 012 045 078 034
6134 034 080 055 078 045
7874 060 100 056 078 078
8026 070 010 066 078 056
9893 034 009 077 078 020
1947 045 040 088 078 055
2877 055 050 099 078 080
3189 022 070 100 078 077
4602 089 050 091 078 060
5405 011 011 000 078 010
6999 000 098 089 078 020
Essentially, you have to do the following:
Read Student data from a text file.
Compute High, Low and Average for each quiz.
Print the Student data and display statistical information like High/Low/Average..
Design
This program can be written in one class. But dividing the code into simple and modular classes based on functionality, is
at the heart of Object Oriented Design.
You must learn the concepts covered in the class and find a way to apply.
Please make sure that you put each class in its own .java file.
package lab2;
class Student {
private int SID;
private int scores[] = new int[5];
//write public get and set methods for
//SID and scores
//add methods to print values of instance variables.
}
/************************************************************************************/
package lab2;
class Statistics
{
int [] lowscores = new int [5];
int [] highscores = new int [5];
float [] avgscores = new float [5];
void findlow(Student [] a) {
/* This method will find the lowest score and store it in an array names lowscores. */
}
void findhigh(Student [] a) {
/* This method will find the highest score and store it in an array names highscores. */
}
void findavg(Student [] a) {
/* This method will find avg score for each quiz and store it in an array names avgscores. */
}
//add methods to print values of instance variables.
}
************************************************************************************/
package lab2;
class Util {
Student [] readFile(String filename, Student [] stu) {
//Reads the file and builds student array.
//Open the file using FileReader Object.
//In a loop read a line using readLine method.
//Tokenize each line using StringTokenizer Object
//Each token is converted from String to Integer using parseInt method
//Value is then saved in the right property of Student Object.
}
}
************************************************************************************/
//Putting it together in driver class:
public static void main(String [] args) {
Student lab2 [] = new Student[40];
//Populate the student array
lab2 = Util.readFile("filename.txt", lab2);
Statistics statlab2 = new Statistics();
statlab2.findlow(lab2);
//add calls to findhigh and find average
//Print the data and statistics
}
Topics to Learn
Working with Text Files
//ReadSource.java -- shows how to work with readLine and FileReader
public class ReadSource {
public static void main(String[] arguments) {
try {
FileReader file = new FileReader("ReadSource.java");
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else
System.out.println(line);
}
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}
//How do you tokenize a String? You can use other ways of doing this, if you like.
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
//How to convert a String to an Integer
int x = Integer.parseInt(String) ;
Explanation / Answer
Since the requirements are very simple and straight forward, the code that you have implemented looks good to me since it takes care if every requirement correctly. Had the requirements be more specific, I would have included comments to make it more precise and specific.
CODE
===================
import fileIO.Util;
import model.Statistics;
import model.Student;
import model.StudentReport;
import adapter.Print;
public class Driver {
/**
* Create Object of StudentReport class and Process the Student report.
*/
public static void main(String[] args) {
StudentReport report = new StudentReport();
report.process();
}
}
------------------------------------------------------------------------------------------------------
package model;
import adapter.Print;
import fileIO.Util;
public class StudentReport {
/**
* Function to process the Student Reports.
*
* 1. Read the Data from input file Scores.txt and load into an array of students.
* 2. Serialize the students to a file
* 3. Use Print class functions to display entire student report.
* 4. use randomly picked students and print their individual report.
*/
public void process()
{
// Load File
Student students[] = Util.readFile("Scores.txt");
// Serialize
Util.serializeStudents(students);
// Print Statistics
Print printer = new Print();
printer.printStats();
//Randomly pick some students and print their individual reports.
System.out.println(" Randomly selected Student Reports: ");
for(int i=0; i<5; i++)
{
// Randomly student
int index = (int)(Math.random() * students.length);
System.out.println("Randomly Picked Student ID: "+ students[i].getSID());
// print the student
printer.printStudentScores(students[i].getSID());
System.out.println();
}
}
}
-------------------------------------------------------------------------------------------------------
package model;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = -123433434343L;
private int SID;
private int scores[] = new int[5];
// getter and setter functions
public int getSID() {
return this.SID;
}
// setter function
public void setSID(int id) {
this.SID = id;
}
// Get scores
public int[] getScores() {
return this.scores;
}
// set scores
public void setScores(int[] s) {
// Make deep copy
for (int i = 0; i < s.length; i++) {
this.scores[i] = s[i];
}
}
/**
* Function to determine the highest score of this student.
*
* @return highest
*/
public int getHighest() {
int highest = scores[0];
for (Integer i : scores) {
if (i > highest) {
highest = i;
}
}
return highest;
}
/**
* Function to determine the lowest score of this student.
*
* @return lowest
*/
public int getLowest() {
int lowest = scores[0];
for (Integer i : scores) {
if (i < lowest) {
lowest = i;
}
}
return lowest;
}
/**
* Function compute the average for the student
*
* @return average
*/
public double calcAverage() {
double sum = 0;
for (Integer i : scores) {
sum += i;
}
return sum / scores.length;
}
/**
* Function to determine the grade of the student.
*
* @return grade
*/
public String getGrade() {
double average = calcAverage();
if (average >= 90)
return "A";
else if (average >= 80)
return "B";
else if (average >= 70)
return "D";
else if (average >= 60)
return "D";
else
return "F";
}
// print all data of a student
public void printData() {
System.out.println("Student ID: " + SID);
String str = "Scores: ";
for (int i = 0; i < scores.length; i++) {
str += String.valueOf(scores[i]) + " ";
}
System.out.println(str);
System.out.println("Lowest Marks: " + getLowest());
System.out.println("Highest Marks: " + getHighest());
System.out.println("Average Marks: " + calcAverage());
System.out.println("Letter Grade: " + getGrade());
}
}
------------------------------------------------------------------------------------------------------
package model;
public class Statistics {
// store lowest scores of students
private int[] lowScores;
// store highest scores of students
private int[] highScores;
// store averages of students
private double[] avgScores;
// store grades of students
private String[] grades;
/**
* Function to determine the lowest scores of the students. Store them into
* an array.
*
* @param students
*/
private void calcLowest(Student[] students) {
// allocate memory
lowScores = new int[students.length];
// for each student
for (int i = 0; i < students.length; i++) {
lowScores[i] = students[i].getLowest();
}
}
/**
* Function to determine the High scores of all the students.
*
* @param students
*/
private void calcHighest(Student[] students) {
// allocate memory
highScores = new int[students.length];
// for each student
for (int i = 0; i < students.length; i++) {
highScores[i] = students[i].getHighest();
}
}
/**
* Function o compute the average and grades of all the students.
*
* @param students
*/
private void calculateAverages(Student[] students) {
// allocate memory
avgScores = new double[students.length];
grades = new String[students.length];
// for each student
for (int i = 0; i < students.length; i++) {
// compute average
avgScores[i] = students[i].calcAverage();
// compute average
grades[i] = students[i].getGrade();
}
}
// print statistics for all students and all quizzes
public void printStatistics(Student[] students) {
calcLowest(students);
calcHighest(students);
calculateAverages(students);
// Build header row
String output = "";
output += String.format("%-12s %-15s %-15s %-15s %s%n", "Student ID", "Highest Score", "Lowest Score",
"Aveage Score", "Grade");
for (int i = 0; i < students.length; i++) {
output += String.format("%-12d %-15d %-15d %-15.2f %s%n", students[i].getSID(), highScores[i], lowScores[i],
avgScores[i], grades[i]);
}
System.out.println(output);
}
}
------------------------------------------------------------------------------------------------------
package adapter;
import model.Student;
import model.Statistics;
import fileIO.Util;
public class Print implements Printable
{
/**
* Print the Student Statistics, read from the Serialized file.
*/
@Override
public void printStats() {
// Get all the Scores.
Student[] stds = Util.getStudents();
// Statistics object.
Statistics stats = new Statistics();
stats.printStatistics(stds);
}
/**
* Function to print the statistics for a Student, identified by id.
*
* @param id
*/
@Override
public void printStudentScores(int id) {
// Find Student
Student std = Util.getStudentByID(id);
if(std == null)
{
System.out.println("No Such Student exist with ID: " + id);
}
else
{
std.printData();
}
}
}
------------------------------------------------------------------------------------------------------
package adapter;
public interface Printable {
/**
* Print the Student Statistics, read from the Serialized file.
*/
public void printStats();
/**
* Function to print the statistics for a Student, identified by id.
*
* @param id
*/
public void printStudentScores(int id);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.