I need help removing a specific object from an arraylist. I'm creating objects with a unique ID and grade for each object.I'm trying to use this unique ID to remove an object from the arraylist, but am having trouble figuring out why my code isn't working. I have my main Driver class, a superclass, and a subclass.
The subclass is where the object information is passed from and extends the superclass. I thought that since the subclass is extended, it would be able to be defined from there.
The problem that is occurring is line 49 of the superclasss. Eclipse says that getStudentID isn't defined in the class.
I am trying to modify code that my instructor provided in order to locate this unique ID that an object in the arraylist has. I believe I did everything correctly, but the method "locationPerson" doesn't seem to see the getStudentID() method in the subclass.
Here is the code. Any help would be appreciated!
Subclass
public class StudentEnrollee extends ClassSection{
private int grade;
private String studentID;
StudentEnrollee() {
setStudentID("000-000");
setGrade(0);
}
StudentEnrollee(String ID, int theGrade) {
setStudentID(ID);
setGrade(0);
}
//STUDENT ID
public String getStudentID() {
return studentID;
}
public void setStudentID(String theStudentID) {
this.studentID = theStudentID;
}
//STUDENT GRADE
public int getGrade() {
return grade;
}
public void setGrade(int studentGrade) {
this.grade = studentGrade;
}
public String toString() {
return("Student ID : " + studentID + "\n" +
"Student Grade: " + grade);
}
}
Superclass
import java.util.ArrayList;
import java.util.List;
public class ClassSection {
private int crn, courseNumber, capacity, enrollment, ID, student;
private String departmentCode, courseMode, meetingDay, meetingTime;
//CONSTRUCTOR
ClassSection() {
setCrn(0);
setDepartmentCode("");
setCourseNumber(0);
setCourseMode("");
setMeetingDay("");
setMeetingTime("");
setCapacity(0);
setEnrollment(0);
setID(0);
}
ClassSection(int crn, String departmentCode, int courseNumber, String courseMode, String meetingDay, String meetingTime, int capacity, int enrollment, int ID) {
setCrn(crn);
setDepartmentCode(departmentCode);
setCourseNumber(courseNumber);
setCourseMode(courseMode);
setMeetingDay(meetingDay);
setMeetingTime(meetingTime);
setCapacity(capacity);
setEnrollment(enrollment);
setID(ID);
}
//STUDENT ENROLL ARRAY
List < StudentEnrollee > studentList = new ArrayList < StudentEnrollee > ();
public int getStudent() {
return student;
}
public void addStudent(StudentEnrollee studentObject) {
studentList.add(studentObject);
}
//LOCATING PERSON
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
//Delete person
public void deletePerson(String studentID) {
ClassSection personObject = locatePerson(studentID); // we'll use our locatePerson method find the index of a Person with a given socSecNum.
if (personObject != null) studentList.remove(personObject); // if element i contains the target SSN, remove it.
}
//DISPLAY LIST OF ENROLLEE
public void displayListV1() {
for (int i = 0; i < studentList.size(); i++) // the old way
{
System.out.println(studentList.get(i) + "\n");
}
}
//CRN
public int getCrn() {
return crn;
}
void setCrn(int classCrn) {
this.crn = classCrn;
}
//DEPARTMENT CODE
public String getDepartmentCode() {
return departmentCode;
}
void setDepartmentCode(String classDepartmentCode) {
this.departmentCode = classDepartmentCode;
}
//COURSE NUMBER
public int getCourseNumber() {
return courseNumber;
}
void setCourseNumber(int classCourseNumber) {
this.courseNumber = classCourseNumber;
}
//COURSE LOCATION
public String getCourseMode() {
return courseMode;
}
public void setCourseMode(String classCourseMode) {
this.courseMode = classCourseMode;
}
//MEETING DAY
public String getMeetingDay() {
return meetingDay;
}
public void setMeetingDay(String classMeetingDay) {
this.meetingDay = classMeetingDay;
}
//MEETING TIMES
public String getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(String classMeetingTime) {
this.meetingTime = classMeetingTime;
}
//CAPACITY
public int getCapacity() {
return capacity;
}
public void setCapacity(int classCapacity) {
this.capacity = classCapacity;
}
//ENROLLMENT
public int getEnrollment() {
return enrollment;
}
public void setEnrollment(int classEnrollment) {
this.enrollment = classEnrollment;
}
//INSTRUCTOR ID
public int getID() {
return ID;
}
public void setID(int instructorID) {
this.ID = instructorID;
}
//TO STRING METHOD
public String toString() {
return ("CRN :" + crn + "\n" +
"Department :" + departmentCode + "\n" +
"Course Number :" + courseNumber + "\n" +
"Instructional mode :" + courseMode + "\n" +
"Meeting days :" + meetingDay + "\n" +
"Meeting times :" + meetingTime + "\n" +
"Capacity :" + capacity + "\n" +
"Enrollment :" + enrollment + "\n" +
"Instructor’s ID :" + ID + "\n");
}
}
Driver
public class ClassDriver {
public static void main(String[] args) {
ClassSection firstInstance = new ClassSection(20008, "CHM", 000, "Online", "N/A", "N/A", 30, 21, 231);
ClassSection secondInstance = new ClassSection();
ClassSection addToList = new ClassSection();
StudentEnrollee studentObj1 = new StudentEnrollee();
StudentEnrollee studentObj2 = new StudentEnrollee();
StudentEnrollee studentObj3 = new StudentEnrollee();
studentObj1.setGrade(5);
studentObj1.setID(230);
studentObj2.setGrade(76);
studentObj2.setID(45);
studentObj3.setGrade(2);
studentObj3.setID(34);
addToList.addStudent(studentObj1);
addToList.addStudent(studentObj2);
addToList.addStudent(studentObj3);
addToList.deletePerson("45");
addToList.displayListV1();
System.out.println(firstInstance.toString());
System.out.println(secondInstance.toString());
}
}
I think it should be:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
You are trying to use a method from subclass in superclass, so you got the error that this method is not defined. You can use all method of superclass in subclasses, but it doesn't work another way.
The getStudentID() method is declared in class StudentEnrollee. In the code below, personObject, which is defined as a ClassSection object, does not have access to it.
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
The solution can vary based on your program logic, but the straightforward way is to replace ClassSection with StudentEnrollee:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
Related
I'm looking for help on an error that I am getting while trying to create this java class. I want to add test scores as well as the average for this student class. I have tried a lot of things and I cant seem to get the error "Variable declaratorid expected after this method" to go away when I reach my setTestScore method shown below (shown with arrows) similarly in my next getTestScore method I have an error "cant invoke getTest() on the primitive type int." (also show with arrows)
public class Student {
private String firstName, lastName;
private Address homeAddress, schoolAddress;
private int TestScore, testScores ;
private int testScore1, testScore2, testScore3;;
public void TestScore(int testScore1, int testScore2, int testScore3)
{
this.testScore1 = testScore1;
this.testScore2 = testScore2;
this.testScore3 = testScore3;
}
public Student(String first, String last, Address home, Address school)
{
this.firstName = first;
this.lastName = last;
this.homeAddress = home;
this.schoolAddress = school;
}
testScores = new TestScore(testScore1, testScore2, testScore3);
public void setTestScore(int testNumber, int TestScore) {
if(testNumber==1) {
testScores.setTest1(>>testScore<<);
}
else if(testNumber==2) {
testScores.setTest2(>>testScore<<);
}
else if(testNumber==3) {
testScores.setTest3(>>testScore<<);
}
}
public void setTest1(int test1) {
this.testScore1 = test1;
}
public void setTest2(int test2) {
this.testScore2 = test2;
}
public void setTest3(int test3) {
this.testScore3 = test3;
}
public int getTestScore(int testNumber) {
if(testNumber==1) {
return >>testScores.getTest1<<();
}
else if(testNumber==2) {
return >>testScores.getTest2<<();
}
else if(testNumber==3) {
return >>testScores.getTest3<<();
}
else {
return 0;
}
}
public int getTest1() {
return testScore1;
}
public int getTest2() {
return testScore2;
}
public int getTest3() {
return testScore3;
}
public double getAverageTestScores() {
double avg;
avg=(testScores.getTest1() + testScores.getTest2() + testScores.getTest3())/3.0;
return avg;
}
public String toString()
{
String result;
result = firstName + " " + lastName + "\n";
result += "Home Address:\n" + homeAddress + "\n";
result += "School Address:\n" + schoolAddress + "\n";
result +="Test Score 1:\n" + testScores.getTest1() + "\n";
result +="Test Score 2:\n" + testScores.getTest2() + "\n";
result +="TestScore 3:\n" + testScores.getTest3() + "\n";
result +="Average test score:\n" + getAverageTestScores() + "\n";
return result;
}
}
remove this statement
testScores = new TestScore(testScore1, testScore2, testScore3);
and where ever you have used
testScores.foo
in your program,replace it with
this.foo
remove this statement
testScores = new TestScore(testScore1, testScore2, testScore3);
and where ever you have used
testScores.foo
in your program,replace it with
this.foo
I'm a little unclear on how to make this method. it has to make a method called setCapacity that later can override. I have to "Modify the class Vehicle, the base class, to include a method called setCapacity which
allows the engine capacity to be changed"
class Vehicle {
void setCapactiy1 () {
int setCapactity == 0;
}
}
int capacity;
String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}
#Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
#Override
}
class Task2 {
public static void main(String[] args) {
Car car1 = new Car(1200,"Holden","sedan","Barina");
Car car2 = new Car(1500,"Mazda","sedan","323");
car1.print();
car2.print();
}
}
Seems like a basic setter... It should go like
public void setCapacity(int newCapacity) {
this.capacity = newCapacity;
}
How do you call the parents constructor and give the parent constructor a parameter of 50? I need to make a constructor for HoldenDB which as no formal parameter and calls its parents constructor.
I have started by extending HoldeDB to VechicleDB, however, I'm unsure how to proceed for there.
If someone could help me that would be much appreciated.
import java.util.ArrayList;
class Vehicle {
int capacity;
String make;
void setCapacity(int setCapacity) {
this.capacity = setCapacity;
System.out.println("New Capacity = " + setCapacity);
}
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}
#Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
#Override
public void setCapacity(int setCapacity) {
System.out.println("Cannot change capacity of a car");
}
}
class VehicleDB {
ArrayList<Vehicle> db = new ArrayList<Vehicle>();
void addVehicle(Vehicle c){
db.add(c);
}
void print(){
System.out.println("=== Vehicle Data Base ===");
for(Vehicle v: db){
v.print();
}
}
}
class HoldenDB extends VehicleDB {
void addCar(Vehicle c){
db.add(c);
}
}
class Task5 {
public static void main (String[]args){
HoldenDB db = new HoldenDB ();
db.addCar(1200,"sedan","Barina");
db.addCar(3800,"wagon","Commodore");
db.print();
}
}
public class VehicleDB {
private int n;
public VehicleDB(int n) {
this.n = n;
}
}
public class HoldenDB extends VehicleDB {
public HoldenDB() {
super(50);
}
}
Ok so basically this is my program it's about Students & Student Groups;
Each student has a name, ID and marks/points;
The program is working fine but what's missing is that the SUM function in the class StudentsGroup needs to be static and to take a parameter of the "Group" of which you need the sum of points. My problem is that when I put the function and the ArrayList to static, the function returns both of the groups score combined and I don't know how to make it work
//the program works correctly and returns the correct values about
everything; i only get those errors when i try to change the
sumOfPoints function to static
the two files that i have are:
Group 1:
61662126 Laurel 50
61662213 Mark 35.5
61662345 Yanny 67
61662127 Larry 27
61662125 Kevin 87.5
and Group 2:
61662126 Jason 70
61662213 Josh 25.5
61662345 Bobby 57
61662127 Megan 17
61662125 Drake 86.5
the correct output should be:
Total points of Group1: 267.0
Total points of Group2: 256.0
Comparing Group1 to Group2: 1
but when i put it to static it returns 523 in both which is both of the groups combined and i don't understand what im doing wrong
public interface IFile
{
public void Load();
}
public class Student implements Comparable<Student>
{
private int facnum;
private String name;
private double points;
public Student(int fn, String n, double p)
{
this.facnum = fn;
this.name = n;
this.points = p;
}
public void SetFN(int fn)
{
this.facnum = fn;
}
public void SetName(String n)
{
this.name = n;
}
public void SetPoints(double p)
{
this.points = p;
}
public int GetFN()
{
return this.facnum;
}
public String GetName()
{
return this.name;
}
public double GetPoints()
{
return this.points;
}
public boolean equals(Object s)
{
if (this.GetFN() != ((Student)s).GetFN())
{
return false;
}
return true;
}
public int compareTo(Object s)
{
if(this.GetFN() < ((Student)s).GetFN())
{
return -1;
}
if(this.GetFN() > ((Student)s).GetFN())
{
return 1;
}
return 0;
}
public String toString()
{
return "Faculty Number: " + this.facnum + " Name: " + this.name + " Points: " + this.points + " \n";
}
}
import java.io.*;
import java.util.*;
public class StudentsGroup implements IFile, Comparable<Object>
{
private String groupname;
private List<Student>oStudent = new ArrayList<Student>();
public StudentsGroup(String filename)
{
this.groupname = filename;
Load();
}
public void Load(){
try
{
Scanner sc=new Scanner(new File(this.groupname));
while(sc.hasNextLine())
{
oStudent.add(new Student(sc.nextInt(),sc.next(),
sc.nextDouble()));
}
sc.close();
}
catch(IOException e)
{
System.out.println("Input/Output Error...");
}
}
public void printColl()
{
System.out.println(oStudent.toString());
}
public List<Student> sortedListFN()
{
Collections.sort(oStudent);
return oStudent;
}
public double sumOfPoints()
{
double sum = 0.00;
for(Iterator<Student> it= oStudent.iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints() < ((StudentsGroup) s).sumOfPoints())
{
return -1;
}
if(this.sumOfPoints() > ((StudentsGroup) s).sumOfPoints())
{
return 1;
}
return 0;
}
public static void main(String[] args)
{
StudentsGroup oGroup1 = new StudentsGroup("Group1.txt");
oGroup1.printColl();
System.out.println("Sorted order by FN: " + oGroup1.sortedListFN() + "\n");
StudentsGroup oGroup2 = new StudentsGroup("Group2.txt");
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints() + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints() + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
}
}
edit//the static method that i tried is changing oStudent to static:
private static List<Student>oStudent = new ArrayList<Student>();
obviously changing the sum function to static & editing the compareTo method:
public static double sumOfPoints(Object s)
{
double sum = 0.00;
s = new ArrayList<Student>(oStudent);
for(Iterator<Student> it= ((List<Student>) s).iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints(this) < ((StudentsGroup) s).sumOfPoints(s))
{
return -1;
}
if(this.sumOfPoints(this) > ((StudentsGroup) s).sumOfPoints(s))
{
return 1;
}
return 0;
}
and the output:
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints(oGroup1) + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints(oGroup2) + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
and the output starts returning 523
Your static method overwrites s with the inner object of that particular instance class:
s = new ArrayList<Student>(oStudent);
I think your mistake is here. This is not how you use a static method of class. The correct way to do it is StudentsGroup.sumOfPoints(yourObjectHere). A static method should not know about any field of a particular instance.
I've been having some issues with this program. I have to test out using a driver class each method, but I can't seem to understand what I should do when the parameters are strings.
I had an example for int parameters but the example never showed anything on string parameters and how to convert. Using null makes my driver class run but putting an int or string won't.
What can I do to convert this correctly, so it can display whatever I have in the no parameter constructor?
public class StudentListing
{
private String name;
private String number;
public StudentListing(String n, String num)
{
name = n;
number = num;
}
public StudentListing()
{
name = null;
number = null;
}
public String toString()
{
return("Name is " + name +
"\nNumber is " + number + "\n");
}
public void show()
{
System.out.println(toString());
}
public StudentListing Clone()
{
StudentListing clone = new StudentListing (name, number);
return clone;
}
public int compareTo(String targetKey)
{
return (name.compareTo(targetKey));
}
public void input()
{
name = JOptionPane.showInputDialog("Enter a name");
number = JOptionPane.showInputDialog("Enter a number");
}// end of StudentListing
}//end of class
public class StudentListingDriver
{
public static void main(String[] args)
{
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null,null);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.clone();
s1.show();
}
}
You can have default values and make the no-args constructor call the other constructor.
Use Integer.parseInt(); to convert from a String to an Integer.
You also need to check the conversion for exceptions.
Like this:
public class StudentListing {
private String name;
private int number;
public StudentListing(String n, int num) {
name = n;
number = num;
}
public StudentListing() {
this("defaultName", 0);
}
public String toString() {
return ("Name is " + name + "\nNumber is " + number + "\n");
}
public void show() {
System.out.println(toString());
}
public StudentListing Clone() {
StudentListing clone = new StudentListing(name, number);
return clone;
}
public int compareTo(String targetKey) {
return (name.compareTo(targetKey));
}
public void input() {
name = JOptionPane.showInputDialog("Enter a name");
number = Integer
.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
The tester:
public class StudentListingDriver {
public static void main(String[] args) {
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null, 0);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.Clone();
s1.show();
}
}