Call non static methods from another class in constructor - java

I have a car class and its constructor looks like this:
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
this.position = position;
this.assignedTo = assignedTo;
this.currTime = currTime;
}
The constructor is initialized in another class(main) when I press for create car from the menu.
The parameters of the constructor are all created/initiated by methods in the car class. The system should be the one giving the information like(the ID, position and time in).
The problem is that the car object have not be initialized yet so I can't get the methods to work.
But I really need the cars object to contain its information(like car ID:CR1).
The information are all strings except for the time.
How can I do that?
PS: Im new to programming. At first I was using static but it turns out static methods cause another bigger trouble with my code.
I posted something where there was my static methods and everyone told me to remove the statics.
public void addCar() {
Cars car1 = new Cars(car1.getID(), car1.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car1);
if(!(car1.getAssignedTo()).equals(null)){
car1.getAssignedTo().setAssign(car1);
car1.getAssignedTo().setAvailable(false);
}
}
This is what is called when I want to create a new car.
I also put the whole car class in case you need it:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.swing.text.Position;
public class Cars {
private String carID;
private String plateNum;
private String position;
private Attendant assignedTo;
private long currTime;
static ArrayList<String> tempArray2 = new ArrayList<String>();
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
this.position = position;
this.assignedTo = assignedTo;
this.currTime = currTime;
}
public void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
String tempCarID = ("CR" + (x + 1));
tempArray2.add(tempCarID);
}
}
public String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
tempArray2.remove(tempArray2.get(x));
getPos(tempPos);
//tempArray2.get(x) = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public static String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
#Override
public String toString() {
return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId()
+ "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}
}

I attach you a code that can help you:
first as all the parameters can be statics i move then to the constructor.
second i move the static method "createCarsID();" to a static init block, in order to avoid unwanted calls.
The example is fully functional.
package test;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.swing.text.Position;
public class Cars {
private String carID;
private String plateNum;
private String position;
private Attendant assignedTo;
private long currTime;
static ArrayList<String> tempArray2 = new ArrayList<String>();
static{
createCarsID();
}
public Cars() {
this.carID = Cars.getID();
this.plateNum = Cars.askCarID();
this.position = Cars.generatePosition();
this.assignedTo = Attendant.askForAtt();
this.currTime = System.currentTimeMillis();
}
public static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
String tempCarID = ("CR" + (x + 1));
tempArray2.add(tempCarID);
}
}
public static String getID() {
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
//tempArray2.remove(tempArray2.get(x));
//getPos(tempPos);
//tempArray2.get(x) = null;
break;
}
}
return tempID;
}
public static String generatePosition() {
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
tempArray2.remove(tempArray2.get(x));
return getPos(tempPos);
//tempArray2.get(x) = null;
}
}
return null;
}
public static String getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
return "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
#Override
public String toString() {
return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId()
+ "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}
}
Finally in order to call this function:
package test;
public class main {
public static void main(String [] args){
main test = new main();
test.addCar();
}
public void addCar() {
Cars car1 = new Cars();
Garage myGarage = new Garage();
myGarage.add(car1);
if(!(car1.getAssignedTo()).equals(null)){
car1.getAssignedTo().setAssign(car1);
car1.getAssignedTo().setAvailable(false);
}
}
}

Related

Why is it throwing this error: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The code is throwing the following error: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space.
Its definitely this part of the code (and where it leads to):
for (int idx = 1; idx <= 30; idx++) {
simulation.moveToNextStation();
}
Looks like there's a loop that is not being exited out of.
Stack Trace:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Arrays.copyOf(Arrays.java:3511)
at java.base/java.util.Arrays.copyOf(Arrays.java:3480)
at java.base/java.util.ArrayList.grow(ArrayList.java:237)
at java.base/java.util.ArrayList.grow(ArrayList.java:244)
at java.base/java.util.ArrayList.add(ArrayList.java:454)
at java.base/java.util.ArrayList.add(ArrayList.java:467)
at com.easy.remember.Station.addCars(Station.java:37)
at com.easy.remember.Simulation.moveToNextStation(Simulation.java:80)
at com.easy.remember.Simulation.main(Simulation.java:103)
Car class:
package com.easy.remember;
import java.util.*;
public class Car
{
private Station destination;
private Station currentStation;
private Station startStation;
private int currentPassengers;
private static final int CAPACITY = 3;
private ArrayList<Passenger> passengers;
private int revenueCollected;
public Car(Station startStation, Station currentStation, Station destination)
{
this.startStation = startStation;
this.currentStation = currentStation;
this.destination = destination;
currentPassengers = 0;
revenueCollected = 0;
passengers = new ArrayList<>();
}
public boolean pickPassenger(Passenger passenger)
{
if(!spaceAvailable())
return false;
passengers.add(passenger);
currentPassengers++;
return true;
}
public void dropPassenger()
{
if(passengers.isEmpty())
return;
for(int idx = 0; idx < passengers.size(); idx++)
{
Passenger currentPassenger = passengers.get(idx);
if(currentPassenger.checkDestinationReached(currentStation))
{
revenueCollected += currentPassenger.payFare();
passengers.remove(idx--);
currentPassengers--;
}
}
}
public boolean spaceAvailable()
{
return currentPassengers < CAPACITY;
}
public int getRevenueCollected()
{
return revenueCollected;
}
public int getMilesDriven()
{
return destination.getStationNumber() - startStation.getStationNumber();
}
public void moveToNextStation(Station next)
{
currentStation = next;
}
public boolean isDestinationReached()
{
return currentStation.equals(destination);
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Start Station: " + startStation +
"; current Station: " + currentStation + ";Current Number " +
" of Passengers: " + currentPassengers + ";Revenue" + " Collected: " + revenueCollected);
return sb.toString();
}
public int getCurrentPassengers()
{
return currentPassengers;
}
public Station getDestination()
{
return destination;
}
public ArrayList<Passenger>getPassengers()
{
return passengers;
}
}
Passenger class:
package com.easy.remember;
public class Passenger
{
private Station destination;
private Station startStation;
public Passenger(Station startStation, Station destination)
{
this.startStation = startStation;
this.destination = destination;
}
public Station getDestination()
{
return destination;
}
public Station getStartStation()
{
return startStation;
}
public boolean checkDestinationReached(Station currentStation)
{
return destination.equals(currentStation);
}
public int payFare()
{
return destination.getStationNumber() - startStation.getStationNumber();
}
public String toString()
{
return "Start Station: " + startStation + " Destination: " + destination;
}
}
Station class:
package com.easy.remember;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class Station
{
private ArrayList<Car> cars;
private ArrayList<Passenger>passengers;
private int totalRevenueGenerated;
private int totalMiles;
private final int stationNumber;
public Station(int stationNumber)
{
cars = new ArrayList<>();
passengers = new ArrayList<>();
totalRevenueGenerated = 0;
totalMiles = 0;
this.stationNumber = stationNumber;
}
public int getStationNumber()
{
return stationNumber;
}
public void addCar(Car car)
{
cars.add(car);
}
public void addCars(ArrayList<Car>cars)
{
for(Car current: cars)
this.cars.add(current);
}
public void addPassenger(Passenger pass)
{
passengers.add(pass);
}
public int getTotalMiles()
{
return totalMiles;
}
public int getTotalRevenueGenerated()
{
return totalRevenueGenerated;
}
public void collectRevenue()
{
for(int idx = 0; idx < cars.size(); idx++)
{
Car current = cars.get(idx);
if(current.isDestinationReached())
{
totalRevenueGenerated += current.getRevenueCollected();
totalMiles += current.getMilesDriven();
cars.remove(idx--);
}
}
}
public void loadUnloadPassengers()
{
for(int idx = 0; idx < cars.size(); idx++)
{
cars.get(idx).dropPassenger();
}
if(passengers.isEmpty())
return;
for(int idx = 0; idx < cars.size(); idx++)
{
Car current = cars.get(idx);
if(!current.spaceAvailable())
continue;
int requiredPassengers = 3 - current.getCurrentPassengers();
for(int jdx = 0; jdx < requiredPassengers; jdx++)
{
for(int kdx = 0; kdx < passengers.size(); kdx++)
{
if(passengers.get(kdx)
.getDestination()
.getStationNumber() <=
current.getDestination()
.getStationNumber())
{
current.pickPassenger(
passengers.get(kdx));
passengers.remove(kdx--);
break;
}
}
if (!current.spaceAvailable() || passengers.isEmpty())
break;
}
if(passengers.isEmpty())
break;
}
}
public ArrayList<Car> moveCars()
{
return cars;
}
public boolean equals(Object obj)
{
Station rhs = (Station)obj;
return getStationNumber() == rhs.getStationNumber();
}
public void printAllCars()
{
for(Car current : cars)
System.out.println(current);
}
public String toString()
{
return "" + stationNumber;
}
}
Simulation class:
package com.easy.remember;
import java.util.*;
import java.util.Random;
public class Simulation {
private ArrayList<Station> stations;
private int currentStationIndex;
private int miles;
private int revenue;
public Simulation() {
stations = new ArrayList<>();
currentStationIndex = 0;
}
public void addStation(Station station) {
stations.add(station);
}
public Station getStation(int index) {
return stations.get(index);
}
public void generateCars(Station station) {
Random randomGenerator = new Random();
int numCars = randomGenerator.nextInt(30);
for (int idx = 1; idx <= numCars; idx++) {
Car car = null;
int destination = randomGenerator.nextInt(30 - station.getStationNumber() + 1);
car = new Car(station, station, new Station(destination + station.getStationNumber() - 1));
station.addCar(car);
}
}
public int getMiles() {
return miles;
}
public int getRevenue() {
return revenue;
}
public void generatePassengers(Station station) {
Random randomGenerator = new Random();
int numPassengers = randomGenerator.nextInt(60);
for (int idx = 1; idx <= numPassengers; idx++) {
Passenger passenger = null;
int destination = randomGenerator.nextInt(30 - station.getStationNumber() + 1);
passenger = new Passenger(station, new Station(destination + station.getStationNumber() - 1));
station.addPassenger(passenger);
}
}
public void moveToNextStation() {
Station currentStation = stations.get(currentStationIndex++);
Station nextStation = null;
try {
nextStation = stations.get(currentStationIndex);
} catch (Exception except) {
nextStation = null;
}
if(currentStationIndex == 0) {
currentStation.collectRevenue();
} else {
currentStation.loadUnloadPassengers();
currentStation.collectRevenue();
}
revenue += currentStation.getTotalRevenueGenerated();
miles += currentStation.getTotalMiles();
if (nextStation != null) {
ArrayList<Car> carsToMove = currentStation.moveCars();
for (Car current : carsToMove) {
current.moveToNextStation(nextStation);
nextStation.addCars(carsToMove);
}/** */
}
}
public static void main(String[] args) {
Simulation simulation = null;
double totalRevenuePerMile = 0;
//for (int jdx = 1; jdx <= 3; jdx++)
//{
simulation = new Simulation();
for (int idx = 1; idx <= 30; idx++) {
simulation.addStation(new Station(idx));
}
for (int idx = 0; idx < 30; idx++) {
simulation.generateCars(simulation.getStation(idx));
simulation.generatePassengers(simulation.getStation(idx));
}
for (int idx = 1; idx <= 30; idx++) {
simulation.moveToNextStation();
}
double revenuePerMile = ((double) simulation.getRevenue()) / simulation.getMiles();
totalRevenuePerMile += revenuePerMile;
//}
System.out.println("Average revenue per " + " mile in 1000 simulations is: \n" + totalRevenuePerMile);
}
}
This loop seems problematic (in Simulation.moveToNextStation):
ArrayList<Car> carsToMove = currentStation.moveCars();
for (Car current : carsToMove) {
current.moveToNextStation(nextStation);
nextStation.addCars(carsToMove);
}
For the current station, you loop on each car but then add all the cars to the next station for each car. So if you had 30 cars initially then the next station would have 900 cars and then the next station would have 810000 cars...etc. That may lead to an out-of-memory quickly.
At first glance you have 30 cars and 30 stations. If it could have finished you'd have 30^30 cars at the final station: that's roughly 2.05x10^44 cars or over a duodecillion of cars.

Calling a parametrized method from LibraryCollection class to main Class

I am working on library management system project. Below is my LibraryCollection class. I would like to call my findMaterials() and checkOutMaterial() methods in the main class.
I have been trying to call as in below method but I don't get any value in the console.
public static LibraryCollection librarycollectObj1 = new LibraryCollection(10);
String search = null;
librarycollectObj1.findMaterial(search);
Thanks;
//LibraryCollection Class
public class LibraryCollection
{
private int collectionMaxSize;
private Material[] libraryCollection;
public LibraryCollection(int theMaxSize)
{
collectionMaxSize = theMaxSize;
libraryCollection = new Material[collectionMaxSize];
}
public LibraryCollection(int theCollectSize, Material[] theArray)
{
collectionMaxSize = theCollectSize;
libraryCollection = theArray;
}
//(1)----------------Find MATERIAL-----------------
public Material findMaterial(String theFindMaterial)
{
if(theFindMaterial == null)
{
return null;
}
for(int i = 0; i < libraryCollection.length; i++)
{
if(libraryCollection[i] !=null && theFindMaterial.equals(libraryCollection[i].getMaterialId()))
{
return libraryCollection[i];
}
}
return null;
}
//Material ID & checkedOutPtron ID;
public boolean checkOutMaterial(String matrlID, String patronId)
{
Material thisMaterial = findMaterial(matrlID);
if(thisMaterial == null)
{
System.out.println("The material doesn't exist" );
return false;
}
if(thisMaterial.checkedOut())
{
System.out.println("The material has been already checked out " );
return false;
}
thisMaterial.setCheckedOut(true);
thisMaterial.setPatronCheckout(Integer.parseInt(patronId));//Convert string value into int
return true;
}
//Material Class
public class Material
{
private static int materialID = 0 ;
private int mtrId;
private String title;
private boolean checkedOut ;
private int checkedOutPatron;
public Material()
{
mtrId = 0;
title = "";
checkedOut = false;
checkedOutPatron = 0;
}
public Material(int theId, String theTitle)
{
mtrId = theId;
title = theTitle;
}
//Getter Method
public String getMaterialId()
{
return mtrId + "";
}
public String getTitle()
{
return title;
}
public void setCheckedOut(boolean theCheckout)
{
checkedOut = theCheckout;
}
public void setPatronCheckout(int patronCheckout)
{
checkedOutPatron = patronCheckout;
}
public boolean checkedOut()
{
return checkedOut;
}
public int getCheckedOutPatron()
{
return checkedOutPatron;
}
//ToString Method
public String toString()
{
return " \nMaterial ID: " + mtrId + " \nMaterial Title: " + title + " \nChecked Out: "
+ checkedOut + " \nPatron check out: " + checkedOutPatron;
}
public static int getNextID()
{
materialID++;
return materialID;
}
}
When you run:
String search = null
librarycollectObj1.findMaterial(search);
You execute
public Material findMaterial(String theFindMaterial)
{
if(theFindMaterial == null)
{
return null;
}
Since theFindMaterial = search and search = null then you exit the method without doing anything because theFindMaterial = null.
You could do something like this:
public static LibraryCollection librarycollectObj1 = new LibraryCollection(10);
// Initialize the object somehow
for (int i = 0; i < 10; i++) {
librarycollectObj1.libraryCollection[i] = new Material(i, "");
}
String search = "1";
// Do some null checking in production code
System.out.println(librarycollectObj1.findMaterial(search). getMaterialId());

Searching an arraylist for the index of an object with a specific value

I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?
The search function:
public static int studentFinder(ClassSection classOne) {
int studentIndex = 0;
boolean searchAgain = false;
boolean correctStudent = false;
do {
studentIndex = idFinder(classOne);
if (studentIndex == -1) {
System.out.println("That student was not found in the class");
System.out.println("Would you like to search again?");
searchAgain = yesNoBool();
} else {
System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
System.out.println("Is this correct?");
correctStudent = yesNoBool();
if (!correctStudent) {
System.out.println("Would you like to search again?");
searchAgain = yesNoBool();
}
}
} while(searchAgain);
return studentIndex;
}
ID Finder module:
public static int idFinder(ClassSection classOne) {
int studentID = 0;
String intString = "a Student ID to search for:";
int studentIndex = 0;
System.out.println("Please enter a Student ID to search for:");
studentID = intChecker(intString);
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
} else if (studentIdTest != studentID){
studentIndex = -1;
}
}
return studentIndex;
}
The ClassSection class:
import java.util.*;
public class ClassSection {
//instance variables
protected int crnNum = 0;
protected String deptCode = "null";
protected int courseNum = 0;
protected String instructMode = "null";
protected String meetingDays = "null";
protected String meetingTimesStart = "null";
protected String meetingTimesEnd = "null";
protected int classCapacity = 0;
protected int classEnrollment = 0;
protected int instructorID = 0;
protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();
//constructors
public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
int instructorID) {
super();
this.crnNum = crnNum;
this.deptCode = deptCode;
this.courseNum = courseNum;
this.instructMode = instructMode;
this.meetingDays = meetingDays;
this.meetingTimesStart = meetingTimesStart;
this.meetingTimesEnd = meetingTimesEnd;
this.classCapacity = classCapacity;
this.classEnrollment = classEnrollment;
this.instructorID = instructorID;
}
public ClassSection() {
super();
this.crnNum = 0;
this.deptCode = "";
this.courseNum = 0;
this.instructMode = "";
this.meetingDays = "";
this.meetingTimesStart = "";
this.meetingTimesEnd = "";
this.classCapacity = 0;
this.classEnrollment = 0;
this.instructorID = 0;
}
//getters and setters
public void getStudents() {
this.students.forEach(System.out::println);
}
public int getStudentIDByIndex(int index) {
return this.students.get(index).getStudentID();
}
public void addStudent(StudentEnrollee student) {
this.students.add(student);
}
public void removeStudent(int removalIndex) {
this.students.remove(removalIndex);
}
public void changeAddStudentGrade(int studentIndex, int studentGrade) {
this.students.get(studentIndex).setStudentGrade(studentGrade);
}
public int getCrnNum() {
return crnNum;
}
public void setCrnNum(int crnNum) {
this.crnNum = crnNum;
}
public String getDeptCode() {
return deptCode;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public int getCourseNum() {
return courseNum;
}
public void setCourseNum(int courseNum) {
this.courseNum = courseNum;
}
public String getInstructMode() {
return instructMode;
}
public void setInstructMode(String instructMode) {
this.instructMode = instructMode;
}
public String getMeetingDays() {
return meetingDays;
}
public void setMeetingDays(String meetingDays) {
this.meetingDays = meetingDays;
}
public String getMeetingTimesStart() {
return meetingTimesStart;
}
public void setMeetingTimesStart(String meetingTimesStart) {
this.meetingTimesStart = meetingTimesStart;
}
public String getMeetingTimesEnd() {
return meetingTimesEnd;
}
public void setMeetingTimesEnd(String meetingTimesEnd) {
this.meetingTimesEnd = meetingTimesEnd;
}
public int getClassCapacity() {
return classCapacity;
}
public void setClassCapacity(int classCapacity) {
this.classCapacity = classCapacity;
}
public int getClassEnrollment() {
return classEnrollment;
}
public void setClassEnrollment(int classEnrollment) {
this.classEnrollment = classEnrollment;
}
public int getInstructorID() {
return instructorID;
}
public void setInstructorID(int instructorID) {
this.instructorID = instructorID;
}
//mutators
#Override
public String toString() {
return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
+ " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
+ " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
meetingTimesStart, meetingTimesEnd, instructorID);
}
}
The student enrollee class (where the objects in the arraylist are from):
public class StudentEnrollee {
protected int studentID = 0;
protected int studentGrade = 0;
public StudentEnrollee() {
super();
studentID = 0;
studentGrade = 0;
}
public StudentEnrollee(int studentID, int studentGrade) {
super();
this.studentID = studentID;
this.studentGrade = studentGrade;
}
//setters & getters
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(int studentGrade) {
this.studentGrade = studentGrade;
}
#Override
public String toString() {
return String.format("Student ID: %20s \nStudent Grade: %20s \n", studentID, studentGrade);
}
}
The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:
public static int intChecker(String object) {
boolean correctInput = false;
int userInput = 0;
while (!correctInput) {
try {
userInput = scanner.nextInt();
correctInput = true;
} catch(InputMismatchException e) {
System.out.println("I'm sorry, that doesn't seem to be a number");
System.out.println("Please enter " +object);
scanner.next();
}
}
return userInput;
}
public static boolean yesNoBool() {
String yesNo = "";
boolean yesNoBool = false;
System.out.println("Please enter Y/N");
yesNo = scanner.next();
while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
System.out.println("I'm sorry, please enter Y/N");
yesNo = scanner.next();
}
if (yesNo.equalsIgnoreCase("y")) {
yesNoBool = true;
} else if (yesNo.equalsIgnoreCase("n")) {
yesNoBool = false;
}
return yesNoBool;
}
Once you found the match you have to break the loop, otherwise studentIndex gets overwritten for rest of the records for which loop iterating. Also you don't need if(studentIdTest != studentID) just else is also work same.
Add Break in loop in idFinder method as follows:
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
break;
} else{
studentIndex = -1;
}
}
Suggestion: you can intialize studentIndex with -1 instead of setting it in each iteration where match not found.
I hope this will solve your problem.
In your idFinder method, you continue to search for the id even when you find it. In the for loop, you need to stop when you find the id.
Modify your for loop to:
public static int idFinder(ClassSection classOne) {
String intString = "a Student ID to search for:";
int studentIndex = -1; // Initialize the studentIndex to a negative value since 0 is a valid index
System.out.println("Please enter a Student ID to search for:");
int studentID = intChecker(intString);
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
break;
}
}
return studentIndex;
}

Printing data of departments

When I try to print out the data within departments, it prints only the memory of their address.
How can I print the departments and the data?
I want the College department to get all the parameters that are in the Lecturer department. That means that when I create a new College I want it to create a new Lecturer with all the parameters inside.
In College class, I added a method (NewLecturer) that adds an additional Lecturer. Is it written correctly?
public class main {
public static void main(String[] args) {
Lecturer[] L1 = new Lecturer[] { new Lecturer("Dani", 2, "Banana", 1001) };
College FirstCollege = new College("Hmpson", 2, L1);
for (int i = 0; i < L1.length; i++) {
System.out.print(L1[i]);
}
System.out.print(L1);
System.out.print(FirstCollege);
}
}
First class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream, int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer = 10;
}
//Copy constructor
public Lecturer(Lecturer other) {
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Second class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
System.out.print(Object) will call the toString() method of the parameter Object.
The default toString method of Object gives you nothing interesting, so you will have to override toString to fit your needs, for example :
In class Lecturer :
#Override
public String toString() {
return "Lecturer [nameOfLecturer=" + nameOfLecturer + ", numOfTimesPenFalls=" + numOfTimesPenFalls
+ ", favoriteIceCream=" + favoriteIceCream + ", numAuto=" + numAuto + "]";
}
In class College :
#Override
public String toString() {
return "College [CollegeName=" + CollegeName + ", numOfLecturers=" + numOfLecturers + ", allLecturers="
+ Arrays.toString(allLecturers) + "]";
}
create setter / getter and toString method for your Lecturer and College classes.

Cannot run through loop to getAllPassengers

Hey i want to loop through planes to get all passengers and add them to a count to display all passengers for all planes. But im getting an error: Cannot iterate over an array or an instance.
Here is the method:
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : plane.getPassengerNumber())
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
Plane
import java.util.LinkedList;
public class Plane implements Comparable
{
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
public Plane()
{
}
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
public void setOverdue(int overdue) {
this.overdue = overdue;
}
public int getOverdue(){
return overdue;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public boolean isLanded() {
return isLanded;
}
public void setLanded(boolean isLanded) {
this.isLanded = isLanded;
}
public int compareTo(Object arg0) {
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.overdue - p.getOverdue());
}
return 0;
}
public String toString() {
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
passengerNumber is an int. You need to iterate over an Iterable such as an ArrayList:
for (Plane plane: myPlaneList) {
passengers += plane.getPassengerNumber();
}
You are trying to iterate through Plane objects, but your collection is just an int. You'll need a collection of Plane objects
int passengers = 0;
for(Plane plane : myPlanes)
{
passengers += plane.getPassengerNumber();
}
You are trying to iterate over an int, you need to iterate over an java.util.Iterable
Your posted code does not contain the information needed to answer this question.
You are showing us the class Plane, but in order to have more than one plane, you probably have a List<Plane> or a Plane[] somewhere else in the code. Here's one example that would work:
public class Main {
List<Plane> allPlanes; // Load in the omitted code somewhere else
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : allPlanes) // note the change
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
}

Categories

Resources