I have class PERSON and BOUNCYHOUSE which are combined in main method class PARTNERLAB.
I have to add people to the bouncyhouse based on weight limit and if one bouncy house is full, move on to the next.
I get an error that looks like this:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor BouncyHouse() is undefined
at PartnerLab1.main(PartnerLab1.java:17)
How do I define BouncyHouse?
Here's my code:
PARTNER:
public class Person { //encapsulated class the has name and weight
private String name;
private int personWeight;
public Person(String name, int personWeight){ //two argument constructor thta takes in the name and weight and sets both attributes accordingly
this.name= name;
this.personWeight= personWeight;
}
public String getName() //get name
{
return this.name;
}
public int getWeight() //get weight
{
return this.personWeight;
}
public String getInfo(){ //return all info
return "Name: " + this.name +
"\n Person's weight: "+ this.personWeight;
}
BOUNCYHOUSE
import java.util.*;
public class BouncyHouse { //encapsulated class with weight limit and total current weight with all occupants in the bouncy house
private int weightLimit;
private int totalCurrentWeight;
private ArrayList <Person> occupants;
public BouncyHouse(int weightLimit, int totalCurrentWeight, ArrayList<Person> occupants){ //no arguments construction that sets the variable to a default value of 0
this.weightLimit= 0;
this.totalCurrentWeight= 0;
this.occupants = new ArrayList<>();
}
public void setWeightLimit(int weightLimit) //sets weight limit
{
this.weightLimit = weightLimit;
}
public void setTotalCurrentWeight(int totalCurrentWeigth) //sets total current wieght
{
this.totalCurrentWeight = totalCurrentWeigth;
}
public String getInfo() // return all the information about the bouncy house
{
StringBuilder personInfo = new StringBuilder();
for(Person person: occupants)
{
personInfo.append(person.getInfo()+",\n\t");
}
return "BouncyHouse: " +
"\nweightLimit=" + this.weightLimit +
"\ntotalWeight=" + this.totalCurrentWeight +
"\noccupants= " + personInfo.toString(); //can't do it in one sitting !
}
//NEXT: Add a person to the bouncy house
public boolean addPerson(Person person)
{
// check if weight exceeds the limit
if((person.getWeight()+totalCurrentWeight) <= weightLimit)
{
// add person to occupants list
this.occupants.add(person);
// update current total weigh
this.totalCurrentWeight += person.getWeight();
return true;
}
// else, return false
return false;
}
public Person[] addPerson(Person[] persons)
{
Person maxWeightPerson = null;
int maxWeight = 0;
for(int i =0; i < persons.length; i++)
{
// check if weight exceeds the limit
if (!addPerson(persons[i]))
{
if(persons[i].getWeight() < maxWeight)
{
// remove maxWeightPerson from house and add the current person
occupants.remove(maxWeightPerson);
totalCurrentWeight -= maxWeightPerson.getWeight();
// add person to occupants list
this.occupants.add(persons[i]);
maxWeight = 0;
// find next max weight guy
for (Person person : occupants)
{
if (person.getWeight() > maxWeight)
{
maxWeight = person.getWeight();
maxWeightPerson = person;
}
}
}
}
else
{
if(maxWeight < persons[i].getWeight())
{
maxWeight = persons[i].getWeight();
maxWeightPerson = persons[i];
}
}
}
return occupants.toArray(new Person[occupants.size()]);
}
}
PARTNERLAB
import java.util.*;
import java.util.Scanner;
public class PartnerLab1
{
public static void main(String[] args)
{
String choice, name;
int weight;
Scanner in = new Scanner(System.in);
BouncyHouse[] bouncyHouses = new BouncyHouse[2];
for (int i = 0; i < 2; i++)
{
bouncyHouses[i] = new BouncyHouse();
// set weight limits for bouncyHouse
bouncyHouses[i].setWeightLimit(250);
// add persons to houses
do
{
System.out.print("Add person to House " + (i + 1) + " (y/q): ");
choice = in.nextLine();
if (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter weight: ");
weight = Integer.parseInt(in.nextLine());
if (bouncyHouses[i].addPerson(new Person(name, weight)))
{
System.out.println("Person added");
} else
{
System.out.println("Person can't be added. Exceeds weight limit.");
}
}
} while (!choice.equalsIgnoreCase("q"));
}
// display people in houses
for (int i = 0; i < 2; i++)
{
System.out.println("People in House " + i + 1);
System.out.println(bouncyHouses[i].getInfo());
}
}
}
You have defined a parametrized constructor for your BouncyHouse class so you can't call a no-argument constructor without explicitly defining it in your class.
As per the code you have written in main class, You don't required parametrized constructor into BouncyHouse class. You can remove it or in case if you required some where else then add no-argument constructor in BouncyHouse class.
I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.
Whenever I compile my code, I receive the following errors:
constructor SalesPerson in class SalesPerson cannot be applied to
given types; error: constructor Player in class Player cannot be
applied to given types;
But it doesn't list any types. The code in question is
Modify the DemoSalesperson application so each Salesperson has a successive ID number from 111 through 120 and a sales value that ranges from $25,000 to $70,000, increasing by $5,000 for each successive Salesperson. Save the file as DemoSalesperson2.java.*/
SalesPerson class:
public class SalesPerson {
// Data fields for Salesperson include an integer ID number and a double annual sales amount
private int idNumber;
private double salesAmount;
//Methods include a constructor that requires values for both data fields, as well as get and set methods for each of the data fields.
public SalesPerson(int idNum, double salesAmt) {
idNumber = idNum;
salesAmount = salesAmt;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNum) {
idNumber = idNum;
}
public double getSalesAmount() {
return salesAmount;
}
public void setSalesAmount(double salesAmt) {
salesAmount = salesAmt;
}
}
Driver:
public class DemoSalesPerson2 {
public static void main(String[] args) {
SalesPerson s1 = new SalesPerson(111, 0);
final int NUM_PERSON = 10;
SalesPerson[] num = new SalesPerson[NUM_PERSON];
for (int x = 1; x < num.length; x++) {
// NUM_PERSON
num[x] = new SalesPerson((111 + x + "|" + 25000 + 5000 * (x)));
System.out.println(x + " " + s1.getIdNumber() + " " + s1.getSalesAmount());
}
}
}
Change this: num[x] = new SalesPerson((111 + x + "|" + 25000 + 5000 * (x)));
to this: num[x] = new SalesPerson((111 + x), (25000 + 5000 * (x)));
You had it right here SalesPerson s1 = new SalesPerson(111, 0);.
Notice the difference between the two constructor calls.
As Sssss pointed out, you're handing in a String as the constructor param when your method requires two ints.
Code jotted down here, haven't tested it. Should get you pointed in the right direction however.
public class DemoSalesPerson2
{
public static void main(String[] args)
{
SalesPerson[] num = new SalesPerson[10];
final int START_NUM =111;
final double START_SALARY=25_000;
for (int x =0; x<num.length; x++) {
num[x] =new SalesPerson(START_NUM+x,START_SALARY+5000*(x));
System.out.println(num[x].getIdNumber()+" "+num[x].getSalesAmount() );
}
}}
try this!!
I have this assignment that I need use a static method to get student IDs then within that static method evaluate them if the students have passed or failed their classes. It is a bit challenging for me because the static method should only take one argument.
Can this be accomplished by not changing private variables to private static variables?
Any direction is much appreciated.
import java.util.ArrayList;
public class Grade {
public static void main(String[] args) {
ArrayList<GradeDetail> gradeList = new ArrayList<GradeDetail>() ;
System.out.println("Student ID: ");
for(String s : args) {
boolean match = false;
for(GradeDetail grade : GradeDetail.values()) {
if(s.equals(grade.getCode())) {
gradeList.add(grade);
match = true;
}
}
if(!match) {
System.out.printf("unknown student ID entered!");
}
}
System.out.println("Students who passed: ");
//Some function here
System.out.println("Students who failed: ")
//Some function here
return;
}
}
enum GradeDetail {
JOHN (101, 90)
, ROB (102, 50)
, JAMES (103, 55)
;
private final int studentID;
private final int studentGrade;
GradeDetail(int id, int sGrade) {
studentID = id;
studentGrade = sGrade;
}
public int getID() {return studentID;}
public int getGrade() {return studentGrade;}
}
I honestly don't know how to go about this..
Enums are for Static data such as the value of the grade A, B, C. You would never store transient values like John's grade in an Enum. Why don't you try using the enum for the static values.
enum GradeRange {
A (100, 90),
B (89, 80),
C (79, 70);
private final int high;
private final int low;
GradeRange(int high, int low) {
high = high;
low = low;
}
public GradeRange getGrade(int percent) {
for (GradeRange gradeRange : GradeRange.values() {
if (percent <= high && percent >= low)
return gradeRange;
}
}
}
PS - I did not test this code
It would be appropriate to store your data in a class like
class GradeDetail {
public final String sName ;
public final int iId ;
public final int iGrade;
public GradeDetail(String s_name, int i_id, int i_grade) {
sName = s_name;
iId = i_id;
iGrade = i_grade;
}
}
You would then create instances with
GradeDetail gdJohn = new GradeDetail("John", 101, 90)
and access it, for example, with
gdJohn.iGrade;
This should hopefully get you started on the right path.
ERROR: non-static method cannot be referenced from a static context.
In my case the method is called readFile().
Hi. I'm experiencing the same error that countless novice programmers have before, but despite reading about it for hours on end, I can't work out how to apply that knowledge in my situation.
I think the code may need to be restructured so I am including the full text of the class.
I would prefer to house the main() method in small Main class, but have placed it in the same class here for simplicity. I get the same error no matter where I put it.
The readFile() method could easily be placed within the main() method, but I’d prefer to learn how to create small modular methods like this and call them from a main() method.
Originally closeFile() was a separate method too.
The program is supposed to:
open a .dat file
read in from the file data regarding examination results
perform calculations on the information
output the results of the calculations
Each line of the file is information about an individual student.
A single consists of three examination papers.
Most calculations regard individual students.
But some calculations regard the entire collection of students (ie their class).
NB: where the word “class” is used in the code, it refers to academic class of the students, not class in the sense of OO programming.
I have tried various ways to solve problem.
Current approach is to house data concerning a single student examination in an instance of the class “Exam”.
This corresponds to a single line of the input file, plus subsequent calculations concerning other attributes of that instance only.
These attributes are populated with values during the while loop of readFile().
When the while loop ends, the three calculations that concern the entire collection of Exams (ie the entire academic class) are called.
A secondary question is:
Under the comment “Declare Attributes”, I’ve separated the attributes of the class into two subgroups:
Those that I think should be defined as class variables (with keyword static).
Those that I think should be defined as instance variables.
Could you guide me on whether I should add keyword static to those in first group.
A related question is:
Should the methods that perform calculations using the entire collection of instances be declared as static / class methods too?
When I tried that I then got similar errors when these tried to call instance methods.
Thanks.
PS: Regarding this forum:
I have enclosed the code with code blocks, but the Java syntax is not highlighted.
Perhaps it will change after I submit the post.
But if not I'd be happy to reformat it if someone can tell me how.
PPS: this is a homework assignment.
I have created all the code below myself.
The "homework" tag is obsolete, so I didn't use it.
Input File Name: "results.dat"
Input File Path: "C:/Users/ADMIN/Desktop/A1P3E1 Files/results.dat"
Input File Contents (randomly generated data):
573,Kalia,Lindsay,2,8,10
966,Cheryl,Sellers,8,5,3
714,Shea,Wells,7,6,2
206,April,Mullins,8,2,1
240,Buffy,Padilla,3,5,2
709,Yoko,Noel,3,2,5
151,Armand,Morgan,10,9,2
199,Kristen,Workman,2,3,6
321,Iona,Maynard,10,2,8
031,Christen,Short,7,5,3
863,Cameron,Decker,6,4,4
986,Kieran,Harvey,7,6,3
768,Oliver,Rowland,8,9,1
273,Clare,Jacobs,9,2,7
556,Chaim,Sparks,4,9,4
651,Paloma,Hurley,9,3,9
212,Desiree,Hendrix,7,9,10
850,McKenzie,Neal,7,5,6
681,Myra,Ramirez,2,6,10
815,Basil,Bright,7,5,10
Java File Name: "Exam.java"
Java Package Name: "a1p3e1"
Java Project Name: "A1P3E1"
Java File Contents:
/** TODO
* [+] Error Block - Add Finally statement
* [?] studentNumber - change data type to integer (or keep as string)
* [?] Change Scope of to Non-Instance Variables to Static (eg classExamGradeSum)
* [*] Solve "non-static method cannot be referenced from a static context" error
*
*/
package a1p3e1; // Assignment 1 - Part 3 - Exercise 1
import java.io.*;
import java.util.*;
/**
*
* #author
*/
public class Exam {
// (1) Declare Attributes
// (-) Class Attributes
protected Scanner fileIn;
protected Scanner lineIn;
private String line;
private String [] splitLine;
private String InFilePath = "C:/Users/ADMIN/Desktop/A1P3E1 Files/results.dat";
private int fileInRowCount = 20;
private int fileInColumnCount = 6;
private int fileOutRowCount = 20;
private int fileOutColumnCount = 14;
// private int classExamGradeSum = 0;
private int classExamGradeSum;
private double classExamGradeAverage = 0.0;
private int [] classExamGradeFrequency = new int [10];
protected Exam exam [] = new Exam [fileInRowCount];
// (-) Instance Attributes
private String studentNumber;
private String forename;
private String surname;
private int paper1Grade;
private int paper2Grade;
private int paper3Grade;
private String paper1Outcome;
private String paper2Outcome;
private String paper3Outcome;
private int fileInRowID;
private int failCount;
private int gradeAverageRounded;
private int gradeAverageQualified;
private String examOutcome;
// (3) toString Method Overridden
#Override
public String toString () {
return "\n Student Number: " + studentNumber
+ "\n Forename: " + forename
+ "\n Surname: " + surname
+ "\n Paper 1 Grade: " + paper1Grade
+ "\n Paper 2 Grade: " + paper2Grade
+ "\n Paper 3 Grade: " + paper3Grade
+ "\n Paper 1 Outcome: " + paper1Outcome
+ "\n Paper 2 Outcome: " + paper2Outcome
+ "\n Paper 3 Outcome: " + paper3Outcome
+ "\n File In Row ID: " + fileInRowID
+ "\n Fail Count: " + failCount
+ "\n Exam Grade Rounded: " + gradeAverageRounded
+ "\n Exam Grade Qualified: " + gradeAverageQualified
+ "\n Exam Outcome: " + examOutcome;
}
// (4) Accessor Methods
public String getStudentNumber () {
return studentNumber;
}
public String getForename () {
return forename;
}
public String getSurname () {
return surname;
}
public int getPaper1Grade () {
return paper1Grade;
}
public int getPaper2Grade () {
return paper2Grade;
}
public int getPaper3Grade () {
return paper3Grade;
}
public String getPaper1Outcome () {
return paper1Outcome;
}
public String getPaper2Outcome () {
return paper2Outcome;
}
public String getPaper3Outcome () {
return paper3Outcome;
}
public int getFileInRowID () {
return fileInRowID;
}
public int getFailCount () {
return failCount;
}
public int getGradeAverageRounded () {
return gradeAverageRounded;
}
public int getGradeAverageQualified () {
return gradeAverageQualified;
}
public String getExamOutcome () {
return examOutcome;
}
// (5) Mutator Methods
public void setStudentNumber (String studentNumber) {
this.studentNumber = studentNumber;
}
public void setForename (String forename) {
this.forename = forename;
}
public void setSurname (String surname) {
this.surname = surname;
}
public void setPaper1Grade (int paper1Grade) {
this.paper1Grade = paper1Grade;
}
public void setPaper2Grade (int paper2Grade) {
this.paper2Grade = paper2Grade;
}
public void setPaper3Grade (int paper3Grade) {
this.paper3Grade = paper3Grade;
}
public void setPaper1Outcome (String paper1Outcome) {
this.paper1Outcome = paper1Outcome;
}
public void setPaper2Outcome (String paper2Outcome) {
this.paper2Outcome = paper2Outcome;
}
public void setPaper3Outcome (String paper3Outcome) {
this.paper3Outcome = paper3Outcome;
}
public void setFileInRowID (int fileInRowID) {
this.fileInRowID = fileInRowID;
}
public void setFailCount (int failCount) {
this.failCount = failCount;
}
public void setGradeAverageRounded (int gradeAverageRounded) {
this.gradeAverageRounded = gradeAverageRounded;
}
public void setGradeAverageQualified (int gradeAverageQualified) {
this.gradeAverageQualified = gradeAverageQualified;
}
public void setExamOutcome (String examOutcome) {
this.examOutcome = examOutcome;
}
// (2) Constructor Methods
// (-) Constructor Method - No Arguments
public Exam () {
this.studentNumber = "";
this.forename = "";
this.surname = "";
this.paper1Grade = 0;
this.paper2Grade = 0;
this.paper3Grade = 0;
this.paper1Outcome = "";
this.paper2Outcome = "";
this.paper3Outcome = "";
this.fileInRowID = 0;
this.failCount = 0;
this.gradeAverageRounded = 0;
this.gradeAverageQualified = 0;
this.examOutcome = "";
}
// (-) Constructor Method - With Arguments (1)
public Exam (
String studentNumber,
String forename,
String surname,
int paper1Grade,
int paper2Grade,
int paper3Grade,
String paper1Outcome,
String paper2Outcome,
String paper3Outcome,
int fileInRowID,
int failCount,
int gradeAverageRounded,
int gradeAverageQualified,
String examOutcome) {
this.studentNumber = studentNumber;
this.forename = forename;
this.surname = surname;
this.paper1Grade = paper1Grade;
this.paper2Grade = paper2Grade;
this.paper3Grade = paper3Grade;
this.paper1Outcome = paper1Outcome;
this.paper2Outcome = paper2Outcome;
this.paper3Outcome = paper3Outcome;
this.fileInRowID = fileInRowID;
this.failCount = failCount;
this.gradeAverageRounded = gradeAverageRounded;
this.gradeAverageQualified = gradeAverageQualified;
this.examOutcome = examOutcome;
}
// (-) Constructor Method - With Arguments (2)
public Exam (
String studentNumber,
String forename,
String surname,
int paper1Grade,
int paper2Grade,
int paper3Grade) {
this.studentNumber = studentNumber;
this.forename = forename;
this.surname = surname;
this.paper1Grade = paper1Grade;
this.paper2Grade = paper2Grade;
this.paper3Grade = paper3Grade;
this.paper1Outcome = "";
this.paper2Outcome = "";
this.paper3Outcome = "";
this.fileInRowID = 0;
this.failCount = 0;
this.gradeAverageRounded = 0;
this.gradeAverageQualified = 0;
this.examOutcome = "";
}
// (6) Main Method
public static void main (String[] args) throws Exception {
Exam.readFile ();
}
// (7) Other Methods
// (-) Read File Into Instances Of Exam Class
// limitation: hard coded to 6 column source file
public void readFile () throws Exception {
try {
fileIn = new Scanner(new BufferedReader(new FileReader(InFilePath)));
int i = 0;
while (fileIn.hasNextLine ()) {
line = fileIn.nextLine();
splitLine = line.split (",", 6);
// create instances of exam from file data and calculated data
exam [i] = new Exam (
splitLine [0],
splitLine [1],
splitLine [2],
Integer.parseInt (splitLine [3]),
Integer.parseInt (splitLine [4]),
Integer.parseInt (splitLine [5]),
convertGradeToOutcome (paper1Grade),
convertGradeToOutcome (paper2Grade),
convertGradeToOutcome (paper3Grade),
i + 1,
failCount (),
gradeAverageRounded (),
gradeAverageQualified (),
convertGradeToOutcome (gradeAverageQualified));
fileIn.nextLine ();
i ++;
}
classExamGradeFrequency ();
classExamGradeSum ();
classExamGradeAverage ();
// close file
fileIn.close ();
} catch (FileNotFoundException | NumberFormatException e) {
// fileIn.next ();
System.err.println("Error: " + e.getMessage());
//System.out.println ("File Error - IO Exception");
}
for (Exam i : exam) {
System.out.println(i.toString());
System.out.println();
}
// System.out.println(classExamGradeSum);
// System.out.println();
System.out.println(classExamGradeAverage);
System.out.println();
System.out.println(classExamGradeFrequency);
System.out.println();
}
// (-) Fail Count (1 Student, 3 Papers)
public int failCount () {
//
if (paper1Grade > 6){
failCount = failCount + 1;
}
if (paper2Grade > 6){
failCount = failCount + 1;
}
if (paper3Grade > 6){
failCount = failCount + 1;
}
return failCount;
}
// (-) Grade Average Rounded (1 Student, 3 Papers)
public int gradeAverageRounded () {
gradeAverageRounded = (int) Math.ceil(
(paper1Grade + paper2Grade + paper3Grade) / 3);
return gradeAverageRounded;
}
// (-) Grade Average Qualified (1 Student, 3 Papers)
public int gradeAverageQualified (){
gradeAverageQualified = gradeAverageRounded;
if (failCount >= 2 && gradeAverageRounded <= 6) {
gradeAverageQualified = 7;
}
return gradeAverageQualified;
}
// (-) Convert Grade to Outcome (Pass / Fail)
public String convertGradeToOutcome (int grade) {
String outcome;
if (grade <= 6){
outcome = "Pass";
} else if (grade > 6){
outcome = "Fail";
} else {
outcome = "Unknown (Error)";
}
return outcome;
}
// (-) Class Exam Grade Sum (All Students, All Papers)
/** assumption: average grade for class is average of grades awarded,
* using rounded figures, not raw per paper results
*/
public void classExamGradeSum () {
classExamGradeSum = 0;
// for each loop (to iterate through collection of exam instances)
for (Exam i : exam) {
classExamGradeSum = classExamGradeSum + i.gradeAverageQualified;
}
}
// (-) Class Exam Grade Average (All Students, All Papers)
/** assumption: average grade for class is average of grades awarded,
* using rounded figures, not raw per paper results
* assumption: <fileInRowCount> is correct
*/
public double classExamGradeAverage () {
classExamGradeAverage = classExamGradeSum / fileInRowCount;
return classExamGradeAverage;
}
// (-) Class Exam Grade Frequency (Count of Instances of Each Final Grade)
/** Example:
* frequency of average grade "5"
* is stored in array <classExamGradeFrequency [4]>
*/
public void classExamGradeFrequency () {
// for each loop (to iterate through collection of exam instances)
for (Exam i : exam) {
classExamGradeFrequency [i.getGradeAverageQualified () - 1] ++;
}
}
}// endof class
readFile is an instance method. Create an instance of Exam to use:
new Exam().readFile();
Given that the Exam has many instance variables, some of which are used in the readFile method, this method should not be static. (Use of static class variables creates code smell and should not be considered.)
Given that readFile reads multiple entries from the file into many Exam objects, you could split out the read functionality into a new ExamReader class.
Aside: For flexibility use a List instead of a fixed size array
Exam exam [];
could be
List<Exam> examList;