JAVA Inheritance student, undergrad and gradstudent code - java

For a class project I was asked to create three codes.
Student Class
First, the student class containing three Parameters.
Name(String)
TestScores( int array),
Grade(String).
An empty Constructor. sets the Name and Grade to empty Strings. The TestScores Array will be initialised with three zeros.
Another Constructor(String n, int[] tests, String g)- This will set the name, testScores, and grade.
Three methods:
getName() to return the name
getGrade() to return the grade
setGrade() to set grade
getTestAverage() to return the average of the test scores.
This is where I am having difficulty The method computeGrade(), which, if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail".
The second class is called UnderGrad. This class is a subclass of Student.
We had to create an empty Constructor and another Constructor (String n, int[] tests, String g).
We were instructed to override the computeGrade() method so that an UnderGrad() student must get a 70 or higher to pass.
The third class is the GradStudent a subclass of Student.
We have to create 1 instance variable, int MyGradID, and an empty constructor, which calls super, and set the IDs to 0.
And another constructor (String n, int[] tests, String g, int id)- Remember to call the super constructor and set ID.
Again where I am having challenges. We had to write the method getId(), to return the ID number. Again we needed to override the computeGrade() method And, if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail". But if the test average is higher than 90, the grade should be "Pass with distinction".
I have great difficulty with this task. I attached the GradStudent code. Can you find the errors please? I don't fully understand how to override the superclass private instance variables.
public class GradStudent extends Student {
private int MyGradID;
public void GradStudent() {
super();
MyGradID = 0;
}
public void GradStudent(String n, int[] tests, String g, int id) {
super(n, tests, g);
MyGradID = id;
}
public int getId() {
return MyGradID;
}
#Override public void computeGrade() {
if (testScores.getTestAverage() >= 65) {
super.setGrade("Pass");
} else if (testScores.getTestAverage() > 90) {
grade = "Pass with distinction";
}
}
}
This is my Student class. I'm not sure if I am referencing my super class correctly, so I am adding it. Hopefully you can explain it to me.
public class Student {
private String name;
private int[] testScores = new int[3];
private String grade;
public Student() {
name = "";
grade = "";
testScores[0] = 0;
testScores[1] = 0;
testScores[2] = 0;
}
public Student(String n, int[] tests, String g) {
name = n;
testScores = tests;
grade = g;
}
public String getName() {
return name;
}
public String getGrade() {
return grade;
}
public void setGrade(String newGrade) {
grade = newGrade;
}
public int getTestAverage() {
int average = 0;
int count = 0;
for (int testScore : testScores) {
count++;
average = average + testScore;
}
return average / testScores.length;
}
public void computeGrade() {
grade = "Fail";
if (this.getTestAverage() >= 65) {
grade = "Pass";
}
}
}

This question simply wouldn't exist if you had an IDE (or, looked at the feedback from compile). I pasted the code into Eclipse and out popped a lot of problems.
Let's look at GradStudent.
public class GradStudent extends Student {
private int MyGradID;
// Constructors do not return anything.
public GradStudent() {
super();
MyGradID = 0;
}
// Again, constructors do not return anything.
public GradStudent(String n, int[] tests, String g, int id) {
super(n, tests, g);
MyGradID = id;
}
public int getId() {
return MyGradID;
}
// Okay. Override annotation in place. Now, computeGrade() needs to get its data from someplace. Fortunately, we
// have a method in Student to do that for us. That method is called 'getTestAverage()'. You do not need to
// reference the array created in 'Student'.
#Override public void computeGrade() {
int testAverage = getTestAverage();
if (testAverage >= 65) { // Evaluate against that testAverage. There is no method (or parameter) associated
// with an array that will compute its average.
setGrade("Pass");
} else if (testAverage > 90) {
setGrade("Pass with distinction");
}
}
}
The Student class is just fine (though count in getTestAverage() is a pointless variable which doesn't do anything and an int[] is created with all values being initialised to 0).
Now I would question why the instructor would have told you to create a constructor to set the grade... when you don't actually know what the grade is... but whatever.
Where are you having trouble with the computeGrade() method in Student? It seems fine to me. The problem in GradStudent is fixed given the changes made above.

What jumps out at me is
if(testScores.getTestAverage>=65)
Try changing that to
if(testScores.getTestAverage()>=65)
Easy mistake to make. Hope this helps!
Edit - I see that twice.
Also, I don't think constructors should have a return type void (or any) though I could be wrong.

Related

Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement

I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.

Array project seems to only print out null

The program is supposed to assign random values to the Student objects in the studentArr array.
Right now it is only printing out null values. Ive tried several different print methods.
I'm pretty sure its something wrong with either my method that is supposed to fill out each student object's attributes, or with my print statement.
import java.util.*;
public class Lab6Excercise
{
String[] first={"Rick","Morty","Moriarty","Samus","Promethius","Geiger","Moriarti","Bob","Taco",
"Asparagus","Shoes","Potato","Dirty","Dan","Spongebob","Space","Nova","Illadin","Orange","Electron"};
String[] last={"PoopyButthole","Red","Mantis","Toboggan","Oak","Elm","Dumbledore","Potter","Spice","Toothbrush","Argon",
"Blitz","LazerWolf","Mc-BigMac","King","Queen","Spork","Petrolium","Apple","Trash"};
//no syntax errors if set to static, but prints out null for everything.
//problem here or in calling array to print?
public static Student[] studentArr= new Student[20];
public Lab6Excercise(){
initializeArray();
}
public void initializeArray(){
for(int i=0; i>20; i++){
//this one seems correct but it cant find the symbol method- setStudentID etc. methods
// online it said to try (Student)studentArr.setStudentID(id())
//which explicitely casts it
//seems to work
//http://stackoverflow.com/questions/29328569/setting-values-to-an-array-of-objects
studentArr[i]= new Student();
studentArr[i].setStudentID(id());
studentArr[i].setFirstName(First());
studentArr[i].setLastName(Last());
studentArr[i].setGrade(Grades());
//other way?probably wrong
//studentArr[i]= new Student(studentArr.id(),
//studentArr.First(),
//studentArr.Last(),
//studentArr.Grades());
}
}
public Student[] getStudentArr(){
return studentArr;
}
//do i even need this?
//public Lab6Excercise getLab(){
// return lab;
//}
public static void main(String[] args){
//randomly generate double grade, student id;
//create 2 arrays, first name, last name. pull randomly for name generation
//necessary? how do i
Lab6Excercise lab= new Lab6Excercise();
//prints out hash or something
//System.out.println(lab.studentArr.toString());
//prints out nulls
// System.out.println(Arrays.deepToString(studentArr));
for(int i=0; i<studentArr.length; i++){
System.out.println(studentArr[i]);
}
}
public int id(){
int ID=1+(int)(Math.random()*((100-1)+1));
return ID;
}
public String First(){
Random random= new Random();
int index= random.nextInt(first.length);
return first[index];
}
public String Last(){
Random random= new Random();
int index= random.nextInt(last.length);
return last[index];
}
public double Grades(){
double grade=0+(double)(Math.random()*((4-1)+1));
return grade;
}
}
and the object class
import java.util.Random;
public class Student
{
private int studentID;
private String firstName;
private String lastName;
private double grade;
// no-argument constructor calls other constructor with default values
public Student()
{
this( 0, "", "", 0.0 ); // call four-argument constructor
} // end no-argument Student constructor
// initialize a record
public Student( int id, String first, String last, double grade )
{
setStudentID( id );
setFirstName( first );
setLastName( last );
setGrade( grade );
} // end four-argument Student constructor
// set student ID number
public void setStudentID( int id )
{
studentID = id;
} // end method setStudentID
// get student ID number
public int getStudentID()
{
return studentID;
} // end method getStudentID
// set first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set grade
public void setGrade( double gradeValue )
{
grade = gradeValue;
} // end method setGrade
// get grade
public double getGrade()
{
return grade;
} // end method getGrade
public static int getRandom(int[] array){
int rnd= new Random().nextInt(array.length);
return array[rnd];
}
public String toString(){
return "First name: "+firstName + "Last name: " + lastName+ "ID: "+ studentID+ "Grade: " + grade+"\n";
}
}
You never initialize your array, because your for loop indexing is wrong.
for (int i = 0; i > 20; i++)
This says: for i starting at 0, run the following code if i is greater than 20, incrementing the value of i by 1 each time. Since i starts out already being less than 20, it is never greater than 20, and the code never runs. Instead, do the following, making your run-condition i less than 20:
for (int i = 0; i < 20; i++)
Or, better yet:
for (int i = 0; i < studentArr.length; i++)
For more details on the syntax of the for statement, check out the Java documentation.
It's a simple error in your for loop in the initialize array method. The statement: i >20 is the condition under which the loop will execute. But if i starts as 0 it will never be 20 and the loop will never execute. Just change the condition (which is i >20 right now) to i < 20 and it will work. :)

How to change the position within the array

I have one class which is called people where I keep track of 50 people, their rank, name, age and order. Then I have a second class called rearrange where I have to change the position of the int order. So it will change up the order, like order 1 which is in position 0, will be moved to position 48th. I need to do the whole thing without using any loop.
class people {
int order[] = new int[50];
for(int j=0; j<order.length; j++) {
order[j] = "order" + j;
System.out.print(order);
}
}
class rearrange {
// In here i need to change the position of the int order, and need to do this without using any loop.
}
Shouldn't rearrange be a method of the people class? Classes are usually created for Nouns, Verbs are usually functions or methods of a class. And wouldn't it be better to have a class "Person" and make an array of 50 of them, and simply change their index to change their order?
Consider something like this:
public class Person //create Person class with the attributes you listed
{
private int rank;
private int age;
private String name;
public Person(int rank, int age, String name) //constructor
{
this.rank = rank;
this.age = age;
this.name = name;
}
}
public class MainClass
{
Person[] people = new Person[50]; //array of Persons, containing 50 elements
public static void main(String[] args)
{
for(int i = 0; i < people.length(); i++)
{
people[i] = new Person(something, something, something); //give all the people some values, you'll have to decide what values you are giving them
}
//do something with the rearrange function here
}
public static void rearrange(int target, int destination) //this is just a "swap" function
{
Person temp = people[destination];
people[destination] = people[target];
people[target] = temp;
}
}

java - find the max value from a linked list

Disclaimer: I am a very early student and am struggling to learn java. Please tell me if I'm leaving out any important information.
I am writing a program that prompts the user to do various operations to a linked list (add, remove, change value, etc.) but rather than storing a string or some primitive data type I am storing objects of type Student (which basically contains a string for the name of the student and an integer for their test score) and am stuck on how to find the maximum test score since I can't just find the highest Student.
Any help would be appreciated.
Well you can have two variables, one as the currentScore, and another as the newScore. And then traverse through each student object, get the test value, and then compare. If the new score is lower, then keep current. If new score is higher, replace current score with new score, and keep traversing. When you traverse the list, you have the highest score
You can iterate over the list as other answers described or you can use Collections.max method. To use this method your Student class should implement comperable interface.
public class Student implements Comparable<Student>
and you need to add compareTo method to the class:
#Override
public int compareTo(Student student)
{
if (this.score > student.score)
{
return 1;
}
if (this.score < student.score)
{
return -1;
}
else
{
return 0;
}
}
Now when you write Collections.max(list) you will get the Student with the highest score.
I wrote a simple program that matched your case.
Main Class:
import java.util.*;
import java.lang.Math;
public class FindHighestScore
{
public static void main(String[] args)
{
LinkedList<Student> studentLinkedlist = new LinkedList<Student>();
studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing
studentLinkedlist.add(new Student("Jason",5));
studentLinkedlist.add(new Student("Myles",6));
studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score
studentLinkedlist.add(new Student("Kate",4));
int temp = 0; // To store the store temporary for compare purpose
int position = 0; // To store the position of the highest score student
for(int i = 0; i < studentLinkedlist.size(); i ++){
if(studentLinkedlist.get(i).getScore() > temp){
temp = studentLinkedlist.get(i).getScore();
position = i;
}
}
System.out.println("Highest score is: " + studentLinkedlist.get(position).getName());
System.out.println("Score: " + studentLinkedlist.get(position).getScore());
}
}
The student constructor class:
public class Student
{
String name;
int score;
Student(){
}
Student(String name, int score){
this.name = name;
this.score = score;
}
String getName(){
return this.name;
}
int getScore(){
return this.score;
}
}
The above program produce result as follows:
Highest score is: Peter
Score: 10

Setter function with arguments

Alright so I am doing an exercise where I have an object that contains scores for 3 tests.
I then have a set-function that takes 2 arguments, the test number and the score you set to it.
Right now my problem is that I do not know how to make the test number argument work correctly.
The code works if I do test1 = score, but when I put student1.test1 in the set argument, for some reason it does not register.
I hope you can point me in the right direction, I would be really grateful!
I have a main class and a student class:
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
student1.setTestScore(student1.test1, 50);
System.out.print(student1.test1);
}
}
public class Student {
int test1;
int test2 = 0;
int test3;
Student() {
int test1 = 0;
int test2 = 0;
int test3 = 0;
}
public void setTestScore(int testNumber, int score){
testNumber = score;
}
}
Java is a pass by value language, so when you pass student1.test1 to student1.setTestScore, you are passing a copy of that member. You are not passing a reference to the member. Therefore the method can't change the member's value.
Even if the language allowed such modification, it would be a bad idea in terms of object oriented programming, since you normally make members private and don't access them directly from outside the class.
A possible alternative is to use an array :
public class Student {
int[] test = new int[3];
...
public void setTestScore(int testNumber, int score){
if (testNumber >= 0 && testNumber < test.length)
test[testNumber]=score;
}
...
}
and you'd call the method like this :
student1.setTestScore(0, 50); // note that valid test numbers would be 0,1 and 2

Categories

Resources