I am trying to develop java program for finding the shortest path with genetic algorithm in weighted graph. I am having difficulties in coding based on this algorithm. Can someone show me sample codes for this problem. Any language is okay. Any information like libraries or others that might be helpful for this problem is also okay. Most important thing right now is to test the time to find the shortest path based on this algorithm and I need to find out before due date for my assignment. So if anyone can help me,please.
I was coding based on java and I have difficulties mostly in cross over and mutation process. And also defining fitness function is also a problem.
Here is a Java example of a shortest path genetic algorithm
package ga;
import java.util.ArrayList;
import java.util.Arrays;
public class GA {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//computation time
long start = System.nanoTime();
//population size
int populationSize = 30;
//Number of Cities
int numCities = 15;
//Mutation rate
double mutationRate = 0.05;
//Crossover Rate
double crossoverRate = 0.8;
//Choose File path or if false randomly created Path
boolean useFile = false;
//Name the file to be used
String fileName = "Data.txt";
//Current Number of Generations
int numberOfGenerations = 0;
//Stop Condition
int stopAt=2500;
//Population
Population pop;
//use GA or Brute Force
boolean GAuse=true;
//Selecting File mode or Random Mode
if (useFile == false) {
pop = new Population(populationSize, numCities, crossoverRate, mutationRate);
} else {
FileReader file = new FileReader(fileName);
numCities=file.getNumCities();
crossoverRate=file.getCrossoverRate();
mutationRate=file.getMutationRate();
populationSize=file.getCities().length;
Path p = new Path(file.getNumCities());
p.setPath(file.getCities());
pop = new Population(populationSize, numCities, p,crossoverRate ,mutationRate );
}
if(GAuse==true){
//Sorting the population from Finess / Evaluating
pop.FitnessOrder();
//Prints each path ID/Cost/Fitness/City order(with coordinates)
for (int i = 0; i < pop.getPopulation().length; i++) {
System.out.println("Path ID: "+i+" | Cost: "+pop.getPopulation()[i].getCost()+" | Fitness: "+pop.getPopulation()[i].getFitness()+"%");
System.out.print("Path is: ");
for (int j = 0; j < pop.getPopulation()[i].getPath().length; j++) {
System.out.print(pop.getPopulation()[i].getPath()[j].getId() +"("+pop.getPopulation()[i].getPath()[j].getX()+","+pop.getPopulation()[i].getPath()[j].getY()+") ");
}System.out.println("\n -----------------------------------------------------");
}
//Start looking for possible solution
while (numberOfGenerations !=stopAt) {
//Select / Crossover
while (pop.Mate() == false);
//Mutate
for (int i = 0; i < pop.getNextGen().length; i++) {
pop.getNextGen()[i].setPath(pop.Mutation(pop.getNextGen()[i].getPath()));
}
//Setting the new Generation to current Generation
pop.setPopulation(pop.getNextGen());
pop.setDone(0);
//Sorting the new population from Finess / Evaluating
pop.FitnessOrder();
//Incremente number of Generations
numberOfGenerations++;
}
//Prints out the fitness of each path
double valor=0;
for (int i = 0; i < pop.getPopulation().length; i++) {
valor += pop.getPopulation()[i].getFitness();
System.out.println("Value of Fitness: "+pop.getPopulation()[i].getFitness()+"%");
}
System.out.println("");
System.out.println("Total Fitness: "+valor+"%");
System.out.println("\n-----------------------------------------------");
//Prints each path ID/Cost/Fitness/City order(with coordinates)
for (int i = 0; i < pop.getPopulation().length; i++) {
System.out.println("Path ID: "+i+" | Cost: "+pop.getPopulation()[i].getCost()+" | Fitness: "+pop.getPopulation()[i].getFitness()+"%");
System.out.print("Path is: ");
for (int j = 0; j < pop.getPopulation()[i].getPath().length; j++) {
System.out.print(pop.getPopulation()[i].getPath()[j].getId() +"("+pop.getPopulation()[i].getPath()[j].getX()+","+pop.getPopulation()[i].getPath()[j].getY()+") ");
}System.out.println("\n -----------------------------------------------------");
}
}
else{//USING BRUTE FORTE METHOD
FileReader file = new FileReader(fileName);
ArrayList<City> cities = new ArrayList<City>();
for (int i = 0; i <file.getNumCities(); i++) {
cities.add(file.getCities()[i]);
}
ArrayList<City> best = new ArrayList<City>();
Permutations permu = new Permutations();
permu.permutations(cities);
System.out.print("The shortest path is: ");
for (int i = 0; i < permu.getBest().size(); i++) {
System.out.print(permu.getBest().get(i).getId()+"("+permu.getBest().get(i).getX()+","+permu.getBest().get(i).getY()+")");
}
System.out.println("");
System.out.println("It would Cost: "+permu.getCost());
}
long elapsedTime = System.nanoTime() - start;
System.out.println("Algorithm took: "+elapsedTime+" nano seconds to find a solution");
}
}
package ga;
import java.util.ArrayList;
public class Permutations {
private int cost=999999;
private ArrayList<City> best;
public void permutations(ArrayList<City> list){
permutations(null, list, null);
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
public ArrayList<City> getBest() {
return best;
}
public void setBest(ArrayList<City> best) {
this.best = best;
}
public ArrayList<City> permutations(ArrayList<City> prefix, ArrayList<City> suffix, ArrayList<ArrayList<City>> output){
if(prefix == null)
prefix = new ArrayList<City>();
if(output == null)
output = new ArrayList<ArrayList<City>>();
if(suffix.size() == 1){
ArrayList<City> newElement = new ArrayList<City>(prefix);
newElement.addAll(suffix);
int costNow=cost(newElement);
if(costNow<this.cost){
best=newElement;
this.cost=costNow;
}
return best;
}
for(int i = 0; i < suffix.size(); i++){
ArrayList<City> newPrefix = new ArrayList<City>(prefix);
newPrefix.add(suffix.get(i));
ArrayList<City> newSuffix = new ArrayList<City>(suffix);
newSuffix.remove(i);
permutations(newPrefix,newSuffix,output);
}
return best;
}
public int cost(ArrayList<City> path){
int cost=0;
int i=0;
while(i<path.size()-1){
cost+=path.get(i).distance(path.get(i+1).getX(),path.get(i+1).getY());
i++;
}
cost+=path.get(path.size()-1).distance(path.get(0).getX(), path.get(0).getY());
return cost;
}
}
package ga;
import java.util.Random;
public class Path implements Comparable {
private City [] path;
private int numCities;
private int cost;
private int fitness;
public Path(int numCities) {
this.numCities = numCities;
CreatePath();
cost =0;
calculateCost();
fitness =0;
}
public void calculateCost(){
cost=0;
int i=0;
while(i<numCities-1){
cost+=path[i].distance(path[i+1].getX(),path[i+1].getY());
i++;
}
cost+=path[path.length-1].distance(path[0].getX(), path[0].getY());
}
public int getFitness() {
return fitness;
}
public void setFitness(int fitness) {
this.fitness = fitness;
}
public int getCost() {
return cost;
}
public void setCost(int distance) {
this.cost = distance;
}
/* Overload compareTo method */
public int compareTo(Object obj){
Path tmp = (Path) obj;
if(this.cost < tmp.cost){
return 1;
}
else if(this.cost > tmp.cost){
return -1;
}
else{
return 0;
}
}
public void CreatePath(){
path= new City[numCities];
for (int i = 0; i < path.length; i++) {
path[i]=new City(i,RandomNum(1, 99),RandomNum(1, 99));
}
}
public int RandomNum(int min, int max){
return min+ (new Random()).nextInt(max-min);
}
public City[] getPath() {
return path;
}
public void setPath(City[] path) {
this.path = path;
calculateCost();
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
}
package ga;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
public class FileReader {
private int numCities;
private double mutationRate;
private City[] cities;
private int curLine;
private StringTokenizer st;
private int arrayCount;
private int x, y;
private double crossoverRate;
private String fileName;
public FileReader(String fileName) {
numCities = 0;
mutationRate = 0;
City[] cities = new City[0];
curLine = 1;
arrayCount = 0;
this.fileName=fileName;
read();
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
public double getMutationRate() {
return mutationRate;
}
public void setMutationRate(double mutationRate) {
this.mutationRate = mutationRate;
}
public City[] getCities() {
return cities;
}
public void setCities(City[] cities) {
this.cities = cities;
}
public int getCurLine() {
return curLine;
}
public void setCurLine(int curLine) {
this.curLine = curLine;
}
public StringTokenizer getSt() {
return st;
}
public void setSt(StringTokenizer st) {
this.st = st;
}
public int getArrayCount() {
return arrayCount;
}
public void setArrayCount(int arrayCount) {
this.arrayCount = arrayCount;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void read() {
try {
BufferedReader in = new BufferedReader(new java.io.FileReader("./"+fileName));
String line;
try {
while ((line = in.readLine()) != null) {
if (curLine == 1) {
st = new StringTokenizer(line, "=");
st.nextToken();
numCities = Integer.parseInt(st.nextToken());
cities = new City[numCities];
} else if (curLine == 2) {
st = new StringTokenizer(line, "=");
st.nextToken();
mutationRate = Double.parseDouble(st.nextToken());
}else if(curLine==3){
st = new StringTokenizer(line, "=");
st.nextToken();
crossoverRate = Double.parseDouble(st.nextToken());
}
else {
st = new StringTokenizer(line, "|");
st.nextToken();
String a = st.nextToken();
StringTokenizer stmp = new StringTokenizer(a, "=");
stmp.nextToken();
x = Integer.parseInt(stmp.nextToken());
String l = st.nextToken();
stmp = new StringTokenizer(l, "=");
stmp.nextToken();
y = Integer.parseInt(stmp.nextToken());
cities[arrayCount] = new City(arrayCount, x, y);
arrayCount++;
}
curLine++;
}
} catch (Exception e) {
}
} catch (FileNotFoundException e) {
System.out.println("File not found!!");
}
}
public double getCrossoverRate() {
return crossoverRate;
}
public void setCrossoverRate(double crossoverRate) {
this.crossoverRate = crossoverRate;
}
}
package ga;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class Population {
private int populationSize;
private int numCities;
private Path[] population;
private double crossoverRate;
private City[] child1;
private City[] child2;
private double mutationRate;
private Path[] nextGen;
private int done;
public Population(int populationSize, int numCities, double crossoverRage, double mutationRate) {
this.populationSize = populationSize;
this.numCities = numCities;
population = new Path[populationSize];
this.crossoverRate = crossoverRage;
this.mutationRate = mutationRate;
this.nextGen = new Path[populationSize];
Path p = new Path(numCities);
done = 0;
CreatePopulation(p);
}
public Population(int populationSize, int numCities, Path path, double crossoverRage, double mutationRate) {
this.populationSize = populationSize;
this.numCities = numCities;
this.crossoverRate = crossoverRage;
population = new Path[populationSize];
this.mutationRate = mutationRate;
this.nextGen = new Path[populationSize];
done = 0;
CreatePopulation(path);
}
public void CreatePopulation(Path p) {
int i = 0;
while (i < populationSize) {
City[] tmpCity = new City[numCities];
for (int j = 0; j < tmpCity.length; j++) {
tmpCity[j] = p.getPath()[j];
}
Collections.shuffle(Arrays.asList(tmpCity));
Path tmpPath = new Path(numCities);
tmpPath.setPath(tmpCity);
population[i] = tmpPath;
i++;
}
}
public int SelectParent() {
int total = 0;
//Selecting parents
int totalCost = calculateTotalFitness();
int fit = RandomNum(0, totalCost);
int value = 0;
for (int i = 0; i < population.length; i++) {
value += population[i].getFitness();
if (fit <= value) {
return i;
}//if(fit<=value){
}
return -1;
}
public boolean Mate() {
//Generate a random number to check if the parents cross
int check = RandomNum(0, 100);
int parent1 = SelectParent();
int parent2 = SelectParent();
while (parent1 == parent2) {
parent2 = SelectParent();
}
//check if there is going to be a crossover
if (check <= (crossoverRate * 100)) {
int crossoverPoint = RandomNum(0, population[parent1].getPath().length - 1);
child1 = new City[numCities];
child2 = new City[numCities];
//crossing over
for (int i = 0; i < crossoverPoint; i++) {
child1[i] = population[parent2].getPath()[i];
child2[i] = population[parent1].getPath()[i];
}
for (int i = crossoverPoint; i < numCities; i++) {
child1[i] = population[parent1].getPath()[i];
child2[i] = population[parent2].getPath()[i];
}
//Rearrange childs considering city repetition
int cityChild1;
int cityChild2;
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
for (int i = 0; i < crossoverPoint; i++) {
cityChild1 = child1[i].getId();
cityChild2 = child2[i].getId();
//Get the positions of repeated values
for (int j = crossoverPoint; j < numCities; j++) {
if (cityChild1 == child1[j].getId()) {
list1.add(j);
}
if (cityChild2 == child2[j].getId()) {
list2.add(j);
}
}
}
//Find the missing values
for (int i = 0; i < numCities; i++) {
boolean found = false;
//Fixing Child1
for (int j = 0; j < numCities; j++) {
if (population[parent2].getPath()[i] == child1[j]) {
found = true;
break;
}
}
if (found == false) {
child1[list1.remove(list1.size() - 1)] = population[parent2].getPath()[i];
}
found = false;
//Fixing Child2
for (int j = 0; j < numCities; j++) {
if (population[parent1].getPath()[i] == child2[j]) {
found = true;
break;
}
}
if (found == false) {
child2[list2.remove(list2.size() - 1)] = population[parent1].getPath()[i];
}
}
// System.out.print("Parent 1: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(population[parent1].getPath()[i].getId() + " ");
// }
// System.out.print("\nParent 2: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(population[parent2].getPath()[i].getId() + " ");
// }
// System.out.print("\nChild 1: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(child1[i].getId() + " ");
// }
// System.out.print("\nChild 2: ");
// for (int i = 0; i < numCities; i++) {
// if (i == crossoverPoint) {
// System.out.print("| ");
// }
// System.out.print(child2[i].getId() + " ");
// }
// System.out.println("");
//
// //Repeated Values
// for (int i = 0; i < list1.size(); i++) {
// System.out.print(list1.get(i) + " ");
// }
// System.out.println("");
// for (int i = 0; i < list2.size(); i++) {
// System.out.print(list2.get(i) + " ");
// }
if (AddToGenerationCheckFull(child1, child2) == false) {
return false;
} else {
return true;
}
} else {
if (AddToGenerationCheckFull(population[parent1].getPath(), population[parent1].getPath()) == false) {
return false;
} else {
return true;
}
}
}
public int getDone() {
return done;
}
public void setDone(int done) {
this.done = done;
}
public boolean AddToGenerationCheckFull(City[] child1, City[] child2) {
if (done == populationSize) {
return true;
}
Path newGenChild1 = new Path(numCities);
Path newGenChild2 = new Path(numCities);
newGenChild1.setPath(child1);
newGenChild2.setPath(child2);
if (done < populationSize - 2) {
this.nextGen[done] = newGenChild1;
this.nextGen[done + 1] = newGenChild2;
this.done += 2;
return false;
} else if (done == populationSize - 2) {
this.nextGen[done] = newGenChild1;
this.nextGen[done + 1] = newGenChild2;
done += 2;
return true;
} else {
this.nextGen[done] = newGenChild1;
done += 1;
return true;
}
}
public Path[] getNextGen() {
return nextGen;
}
public void setNextGen(Path[] nextGen) {
this.nextGen = nextGen;
}
public City[] Mutation(City[] child) {
int check = RandomNum(0, 100);
//Checks if its going to mutate
if (check <= (mutationRate * 100)) {
//finds the 2 cities that "mutate"
int point1 = RandomNum(0, numCities - 1);
int point2 = RandomNum(0, numCities - 1);
while (point2 == point1) {
point2 = RandomNum(0, numCities - 1);
}
//Cities are switched as result of mutation
City city1 = child[point1];
City city2 = child[point2];
child[point1] = city2;
child[point2] = city1;
}
return child;
}
public int RandomNum(int min, int max) {
return min + (new Random()).nextInt(max - min);
}
public void FitnessOrder() {
Arrays.sort(population);
// double cost = calculateTotalCost();
for (int i = 0; i < population.length; i++) {
// double total = cost - population[i].getCost();
// double fitness = (total * 100) / cost;
// fitness = 100 - fitness;
// population[i].setFitness(fitness);
int lol = 100000 / (population[i].getCost() + 1);
population[i].setFitness(lol);
// System.out.println("Total: "+total + " "+" Cost: "+cost+" "+" Fitness: "+fitness+"%" );
}
}
public int calculateTotalFitness() {
int cost = 0;
for (int i = 0; i < population.length; i++) {
cost += population[i].getFitness();
}
return cost;
}
public double getCrossoverRate() {
return crossoverRate;
}
public void setCrossoverRate(double crossoverRage) {
this.crossoverRate = crossoverRage;
}
public Path[] getPopulation() {
return population;
}
public void setPopulation(Path[] population) {
this.population = population;
}
public int getPopulationSize() {
return populationSize;
}
public void setPopulationSize(int populationSize) {
this.populationSize = populationSize;
}
public int getNumCities() {
return numCities;
}
public void setNumCities(int numCities) {
this.numCities = numCities;
}
}
package ga;
public class City {
private int x;
private int y;
private int id;
public City(int id,int x, int y){
this.x=x;
this.y=y;
this.id=id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int distance(int xOther,int yOther){
return (int) Math.sqrt(((this.x-xOther)*(this.x-xOther))+((this.y-yOther)*(this.y-yOther)));
}
}
Related
I'm working on a project with a friend; we're trying to create an airplane project using a Passenger class for passengers, Airplane class to add in passengers and create the airplane, and a driver class. We've run into an issue where when we add in all the passengers to the airplane and print all details of the airplane, printed values are capturing only the last passenger's information. We're trying to get this for every passenger. Here is the code:
Passenger
public class Passenger {
private String name;
private int birthYear;
private double weight;
private char gender;
private int numCarryOn;
//Default constructor
public Passenger(){
name = "";
birthYear = 1900;
weight = 0.0;
gender = 'u';
numCarryOn = 0;
}
//Alt default constructor
public Passenger(String newName, int newBirthYear, double newWeight, char newGend, int newNumCarryOn){
this.setName(newName);
this.setBirthYear(newBirthYear);
this.setWeight(newWeight);
this.setGender(newGend);
this.setNumCarryOn(newNumCarryOn);
}
//Calculate age
public int calculateAge(int currentYear){
int age = 0;
if (currentYear < birthYear){
return -1;
}
else {
age = currentYear - birthYear;
}
return age;
}
//Gain weight
public void gainWeight(){
weight += 1;
}
//Gain weight based on input
public void gainWeight(double pounds){
if (weight > 0){
weight = weight + pounds;
}
}
//Get birthYear
public int getBirthYear(){
return birthYear;
}
//Get gender
public char getGender(){
return gender;
}
//Get name
public String getName(){
return name;
}
//Get weight
public double getWeight(){
return weight;
}
//Get numCarryOn
public int getNumCarryOn(){
return numCarryOn;
}
//isFemale
public boolean isFemale(){
if (gender == 'f'){
return true;
}
else {
return false;
}
}
//isMale
public boolean isMale(){
if (gender == 'm'){
return true;
}
else {
return false;
}
}
//loseWeight
public void loseWeight(){
if (weight > 0){
weight -= 1;
}
}
//lose weight by value
public void loseWeight(double weight2lose){
if (weight - weight2lose >= 0){
weight -= weight2lose;
}
}
//print
public void printDetails(){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c | NumCarryOn: %2d\n", name, birthYear, weight, gender, numCarryOn);
}
//setGender
public void setGender(char newGender){
if (newGender == 'f' || newGender == 'm') {
this.gender = newGender;
} else {
this.gender = 'u';
}
}
//setName
public void setName(String newName){
name = newName;
}
//setBirthYear
public void setBirthYear(int newBY){
birthYear = newBY;
}
//setWeight
public void setWeight(double newWeight){
if (newWeight < 0){
weight = -1;
}
else {
weight = newWeight;
}
}
//setNumCarryOn
public void setNumCarryOn(int newNumCarryOn){
if (newNumCarryOn < 0){
numCarryOn = 0;
}
else if (newNumCarryOn > 2){
numCarryOn = 2;
}
else {
numCarryOn = newNumCarryOn;
}
}
}
Airplane
public class Airplane {
private Passenger[] passengers;
private String airplaneName;
private int numPassengers;
public int count = 0;
//default constructor
public Airplane(){
airplaneName = "";
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with String input
public Airplane(String otherairplaneName){
airplaneName = otherairplaneName;
passengers = new Passenger[100];
numPassengers = 0;
}
//default constructor with int input
public Airplane(int otherArraySize){
airplaneName = "";
if (otherArraySize < 0){
otherArraySize = 0;
}
passengers = new Passenger[otherArraySize];
numPassengers = 0;
}
//default constructor with String and int input
public Airplane(String otherAirplaneName, int otherArraySize){
airplaneName = otherAirplaneName;
if (otherArraySize < 0){
otherArraySize = 0;
}
passengers = new Passenger[otherArraySize];
numPassengers = 0;
}
//add a passenger
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
passengers[i] = a;
}
}
//resize array for new passengers
private void resizePassengerArray(){
passengers = new Passenger[passengers.length * 2];
}
//get a passenger
public Passenger getPassenger(int passengerIndex){
return passengers[passengerIndex];
}
//getNumPassengers
public int getNumPassengers() {
return count;
}
//getFirstPassenger
public Passenger getFirstPassenger(){
return passengers[0];
}
//getLastPassenger
public Passenger getLastPassenger(){
return passengers[passengers.length - 1];
}
//getPassengers**
public Passenger[] getPassengers(){
return passengers;
}
//setAirplaneName
public void setAirplaneName(String newAirplaneName){
airplaneName = newAirplaneName;
}
//printAllDetails
public void printAllDetails(){
System.out.printf("AirplaneName: %20s | Number of Passengers: %4d | Airplane Size: %4d\n", airplaneName, count, passengers.length);
for (int i = 0; i < count; i++){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c\n", passengers[i].getName(), passengers[i].getBirthYear(), passengers[i].getWeight(), passengers[i].getGender());
}
}
//removePassenger
public Passenger removePassenger(int passengerIndex){
if (passengerIndex != passengers.length - 1){
for (int i = passengerIndex; i < passengers.length - 1; i++){
passengers[i] = passengers[i+1];
}
}
return passengers[passengerIndex];
}
//remove all passengers
public void removeAllPassengers(){
passengers = new Passenger[100];
}
//total weight passengers
public double getTotalWeightOfAllPassengers(){
double weight = 0.0;
for (int i = 0; i < passengers.length; i++){
weight += passengers[i].getWeight();
}
return weight;
}
//avg weight passengers
public double getAverageWeightOfAllPassengers(){
double avg = this.getTotalWeightOfAllPassengers() / numPassengers;
return avg;
}
//num elements above weight
public int getNumberOfPassengersAboveWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.length; i++){
if (passengers[i].getWeight() > weight){
sum += 1;
}
}
return sum;
}
//num elements below weight
public int getNumberOfPassengersBelowWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.length; i++){
if (passengers[i].getWeight() < weight){
sum += 1;
}
}
return sum;
}
//increase weight of passengers
public void increaseWeightOfAllPassengers(){
for (int i = 0; i < passengers.length; i++){
passengers[i].gainWeight();
}
}
//increase weight of passengers with weight input
public void increaseWeightOfAllPassengers(double increaseAmount){
for (int i = 0; i < passengers.length; i++){
passengers[i].gainWeight(increaseAmount);
}
}
}
Driver
public class RunAirplane {
public static void main(String[] args) {
Airplane a1 = new Airplane("Flight 1", 100);
Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);
a1.addPassenger(p1);
a1.count += 1;
a1.addPassenger(p2);
a1.count += 1;
a1.addPassenger(p3);
a1.count += 1;
a1.addPassenger(p4);
a1.count += 1;
a1.addPassenger(p5);
a1.count += 1;
a1.printAllDetails();
//How it should work starting with name
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Here's a screenshot of the incorrect code:
https://imgur.com/TGc0FQa
The addPassenger() method is overwriting every element in the array:
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
passengers[i] = a;
}
}
It should just set the one at the next available index, which happens to be count:
public void addPassenger(Passenger a){
passengers[count++] = a;
}
This also gives you better encapsulation, as you don't have to expose and increment count externally.
this
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
passengers[i] = a;
}
}
Produce every time a Passenger Array full with the same Passenger.
Perhaps this might solve the problem.
public void addPassenger(Passenger a){
for (int i = 0; i < passengers.length; i++){
if((passengers[i-1] !=null)&&((passengers[i] ==null))
{ passengers[i] = a; }
}
}
A better implementation could be with ArrayList
Airplane
public class Airplane {
private ArrayList<Passenger> passengers;
private String airplaneName;
private int numPassengers;
public int count = 0;
//default constructor
public Airplane(){
airplaneName = "";
passengers = new ArrayList();
numPassengers = 0;
}
//default constructor with String input
public Airplane(String otherairplaneName){
airplaneName = otherairplaneName;
passengers = new ArrayList();
numPassengers = 0;
}
//default constructor with String and int input
public Airplane(String otherAirplaneName){
airplaneName = otherAirplaneName;
passengers = new ArrayList();
numPassengers = 0;
}
//add a passenger
public void addPassenger(Passenger a){
passengers.add(a);
}
//get a passenger
public Passenger getPassenger(int passengerIndex){
return passengers[passengerIndex];
}
//getNumPassengers
public int getNumPassengers() {
return count;
}
//getFirstPassenger
public Passenger getFirstPassenger(){
return passengers.get(0);
}
//getLastPassenger
public Passenger getLastPassenger(){
return passengers.get(passengers.size() - 1);
}
//getPassengers**
public ArrayList<Passenger> getPassengers(){
return passengers;
}
//setAirplaneName
public void setAirplaneName(String newAirplaneName){
airplaneName = newAirplaneName;
}
//printAllDetails
public void printAllDetails(){
System.out.printf("AirplaneName: %20s | Number of Passengers: %4d | Airplane Size: %4d\n", airplaneName, count, passengers.size());
for (int i = 0; i < count; i++){
System.out.printf("Name: %20s | Year of Birth: %4d | Weight: %10.2f | Gender: %c\n", passengers.get(i).getName(), passengers[i].get(i).getBirthYear(), passengers[i].get(i).getWeight(), passengers[i].get(i).getGender());
}
}
//removePassenger
public Passenger removePassenger(int passengerIndex){
passengers.remove(passengerIndex);
return passengers.get(passengerIndex);
}
//remove all passengers
public void removeAllPassengers(){
passengers = new ArrayList();
}
//total weight passengers
public double getTotalWeightOfAllPassengers(){
double weight = 0.0;
for (int i = 0; i < passengers.size(); i++){
weight += passengers.get(i).getWeight();
}
return weight;
}
//avg weight passengers
public double getAverageWeightOfAllPassengers(){
double avg = this.getTotalWeightOfAllPassengers() / numPassengers;
return avg;
}
//num elements above weight
public int getNumberOfPassengersAboveWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.size(); i++){
if (passengers.get(i).getWeight() > weight){
sum += 1;
}
}
return sum;
}
//num elements below weight
public int getNumberOfPassengersBelowWeight(double weight){
int sum = 0;
for (int i = 0; i < passengers.size(); i++){
if (passengers.get(i).getWeight() < weight){
sum += 1;
}
}
return sum;
}
//increase weight of passengers
public void increaseWeightOfAllPassengers(){
for (int i = 0; i < passengers.size(); i++){
passengers.get(i).gainWeight();
}
}
//increase weight of passengers with weight input
public void increaseWeightOfAllPassengers(double increaseAmount){
for (int i = 0; i < passengers.size(); i++){
passengers.get(i).gainWeight(increaseAmount);
}
}
}
The issue is in the method addPassenger. You are replacing always the first element.
You can fix in this way:
public void addPassenger(Passenger a){
passengers[count] = a;
count++
}
For better implementation, you can remove count and use numPassengers.
Therefore the method becomes:
public void addPassenger(Passenger a){
passengers[numPassengers] = a;
numPassengers++
}
and the main class:
public class RunAirplane {
public static void main(String[] args) {
Airplane a1 = new Airplane("Flight 1", 100);
Passenger p1 = new Passenger("Albert", 1879, 198.5, 'm', 2);
Passenger p2 = new Passenger("Grace", 1906, 105, 'f', 1);
Passenger p3 = new Passenger("Tim", 1955, 216.3, 'm', 2);
Passenger p4 = new Passenger("Steve", 1955, 160, 'm', 2);
Passenger p5 = new Passenger("Sergey", 1973, 165.35, 'm', 1);
a1.addPassenger(p1);
a1.addPassenger(p2);
a1.addPassenger(p3);
a1.addPassenger(p4);
a1.addPassenger(p5);
a1.printAllDetails();
//How it should work starting with name
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
For the best implementation, you can use List instead of an array for the field passengers:
private List<Passenger> passengers;
public Airplane(){
airplaneName = "";
passengers = new ArrayList<>();
}
public void addPassenger(Passenger a){
passengers.add(a);
}
You can remove the numPassengers and use size:
public int getNumPassengers() {
return passengers.size();
}
I have these two classes:
import java.util.ArrayList;
import java.util.Arrays;
public class Giocatore {
private String nome;
private ArrayList<Cartella> cartelle;
public Giocatore(String nome, int numeroCartelle) {
this.nome = nome;
for (int i = 0; i < numeroCartelle; i++) {
cartelle.add(new Cartella().creazioneCartella());
}
}
#Override
public String toString() {
return "Giocatore" + " nome=" + nome + ", cartelle=" + cartelle + "]";
}
}
and
import java.util.Random;
public class Cartella {
private int[] cartella;
public Cartella() {
cartella = new int[15];
}
public int[] creazioneCartella() {
Random random = new Random();
int n = random.nextInt(90 + 1) + 1;
for (int i = 0; i < cartella.length; i++) {
if (i > 0) {
for (int j = 0; j < i; j++) {
if (n == cartella[j]) {
n = random.nextInt(90 + 1) + 1;
j--;
}
}
}
cartella[i] = n;
}
return cartella;
}
public void stampaCartella() {
for (int i = 0; i < cartella.length; i++) {
System.out.print(cartella[i] + " ");
}
System.out.println();
}
public int[] getCartella() {
return cartella;
}
public void setCartella(int[] cartella) {
this.cartella = cartella;
}
}
i used the class Cartella as an arraylist in Giocatore, now i want to add an array into that arraylist using the method creazioneCartella(), but every time the compiler suggest me to change the method creazioneCartella into an element of Cartella. How can i add that array into that list? i've tried different methods like Arrays.asList(array) but nothing
You want to send your friend a package with different things. Each thing you put inside the package has such parameters as index number, weight and cost. The package has a weight limit. Your goal is to determine which things to put into the package so that the total weight is less than or equal to the package limit and the total cost is as large as possible.
You would prefer to send a package which weights less in case there is more than one package with the same price.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. The input file contains several lines. Each line is one test case.
Each line contains the weight that the package can take (before the colon) and the list of things you need to choose. Each thing is enclosed in parentheses where the 1st number is a thing's index number, the 2nd is its weight and the 3rd is its cost. Eg:
81 : (1,53.38,45)(2,88.62,98) (3,78.48,3)(4,72.30,76) (5,30.18,9)(6,46.34,48)
8 : (1,15.3,34)
75:(1,85.31,29) (2,14.55,74)(3,3.98,16) (4,26.24,55)(5,63.69,52) (6,76.25,75)(7,60.02,74) (8,93.18,35)(9,89.95,78)
56 : (1,90.72,13)(2,33.80,40) (3,43.15,10)(4,37.97,16) (5,46.81,36)(6,48.77,79) (7,81.80,45)(8,19.36,79) (9,6.76,$64)
OUTPUT SAMPLE:
For each set of things that you put into the package provide a list (items’ index numbers are separated by comma).
E.g.
4 //for package1
- //for package2
2,7 //for package3
8,9 //for package4
CONSTRAINTS:
Max weight that a package can take is ≤ 100 There might be up to 15 items you need to choose from Max weight and cost of an item is ≤ 100
Is there a more elegant and easy to understand solution than https://discuss.codechef.com/questions/104934/package-problemin-java
Here is the code (KnapSack):
public class FriendPackageKnapsack {
public static void parserThings(String[] sub2, List<Package> things,
double maxWeight) {
for (int i = 0; i < sub2.length; i++) {
String[] sub3 = (sub2[i].substring(1, sub2[i].length() - 1)).split(",");
int id = Integer.parseInt(sub3[0]);
double weight = Double.parseDouble(sub3[1]);
double cost = Double.parseDouble(sub3[2].substring(1, sub3[2].length()));
if (weight <= maxWeight) {
Package condidat = new Package(id, weight, cost);
things.add(condidat);
}
}
}
public static String getOptimumFor(List<Package> things, int r, int maxWt) {
int indexSolution = 0;
String returnData = "";
double maxWeight = 0;
double maxCost = 0;
int[] data = new int[r];
List<Integer> res = new ArrayList<Integer>();
int[] arr = new int[things.size()];
for (int i = 0; i < things.size(); i++) {
arr[i] = i;
}
getCombination(arr, data, res, 0, 0);
for (int i = 0; i <= res.size() - r; i += r) {
double someWeight = 0;
double someCost = 0;
for (int j = 0; j < r; j++) {
someWeight += things.get(res.get(i + j)).getWeight();
someCost += things.get(res.get(i + j)).getCost();
}
if (someWeight <= maxWt) {
if ((someCost > maxCost)
|| ((someCost == maxCost) && (someWeight <= maxWeight))) {
indexSolution = i;
maxWeight = someWeight;
maxCost = someCost;
}
}
}
for (int k = indexSolution; k < r + indexSolution; k++) {
returnData += res.get(k) + ",";
}
return returnData + maxCost + "," + maxWeight;
}
public static void getCombination(int[] arr, int[] data, List<Integer> res, int start,
int index) {
if (index == data.length) {
for (int j = 0; j < data.length; j++) { res.add(data[j]); }
return;
}
for (int i = start; i < arr.length && arr.length - i >= data.length - index; i++) {
data[index] = arr[i];
getCombination(arr, data, res, i + 1, index + 1);
}
}
public static void main(String[] args) {
File file = new File("packageproblem.txt");
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) { e.printStackTrace(); }
String line = "";
List<Package> things = new ArrayList<>();
try {
while ((line = in.readLine()) != null) {
String s = "";
// Parsing line
String[] sub1 = line.split(" : ");
int N = Integer.parseInt(sub1[0]);
String[] sub2 = sub1[1].split(" ");
if (sub2.length > 1) {
things.clear();
parserThings(sub2, things, N);
double maxCost = 0;
double maxWeight = 0;
for (int i = 1; i <= things.size(); i++) {
String resultat = getOptimumFor(things, i, N);
// System.out.println(resultat);
String[] sub4 = resultat.split(",");
double cost = Double.parseDouble(sub4[sub4.length - 2]);
double weight = Double.parseDouble(sub4[sub4.length - 1]);
if (cost == maxCost) {
if (weight < maxWeight) {
maxCost = cost;
maxWeight = weight;
s = resultat;
}
}
if (cost > maxCost) {
maxCost = cost;
maxWeight = weight;
s = resultat;
}
}
// System.out.println(s);
String[] sub5 = s.split(",");
String ss = "";
for (int i = 0; i < sub5.length - 2; i++) {
ss += things.get(Integer.parseInt(sub5[i])).getId() + ",";
}
if (ss.equals("")) { System.out.println("-"); }
else { System.out.println(ss.substring(0, ss.length() - 1)); }
}
else { System.out.println("-"); }
}
}
catch (IOException e) { e.printStackTrace(); }
}
}
class Package {
private int id;
private double weight;
private double cost;
public Package(int id, double weight, double cost) {
this.id = id;
this.weight = weight;
this.cost = cost;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public double getWeight() { return weight; }
public void setWeight(double weight) { this.weight = weight; }
public double getCost() { return cost; }
public void setCost(double cost) { this.cost = cost; }
}
The code is taken from here.
You can find a full solution of this problem in java here
https://github.com/rantibi/package-challenge
So I have to create a program where I use polymorphism and inheritance to create arrows that point left and arrow and I did that. however, when I created my main class and try to invoke the methods, say for example "LeftArrow.drawHere" to draw the arrow i get errors saying I cannot make a static reference to the non static field "drawHere() from the class LeftArrow". I was wondering then if I can't do that how can I design my main method so it draws the arrows?
here is my code, note that there are several classes but I will post all of them here.
import java.util.Scanner;
public class LeftArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public LeftArrow()
{
super();
tail = 0;
width = 0;
}
public LeftArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth);
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
//System.out.println();
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset());
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside + 1));
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawTail()
{
skipSpaces(getOffset() - getInside() - 1);
System.out.print('*');
skipSpaces(getInside());
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside - 1));
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset());
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
#Override
public void setOffset(int noff) {
// TODO Auto-generated method stub
}
#Override
public int getOffset() {
// TODO Auto-generated method stub
return 0;
}
}
import java.util.Scanner;
public class RightArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public RightArrow()
{
super();
tail = 0;
width = 0;
}
public RightArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth); // must be odd
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
System.out.println();
}
public void drawTail()
{
skipSpaces(getOffset() + 1);
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
skipSpaces(getInside());
System.out.print('*'); // fix
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset() + tail);
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset() + tail);
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
}
public abstract class ShapeBase implements ShapeInterface {
private int offset;
public abstract void drawHere();
public void drawAt(int lineNumber) {
for (int count = 0; count < lineNumber; count++)
System.out.println();
drawHere();
}
}
public class ShapeBasic implements ShapeInterface
{
private int offset;
public ShapeBasic()
{
offset = 0;
}
public ShapeBasic( int noff)
{
offset = noff;
}
public void setOffset(int noff)
{
offset = noff;
}
public int getOffset()
{
return offset;
}
public void drawAt(int linnumber)
{
for (int count = 0; count < linnumber; count++)
System.out.println();
drawHere();
}
public void drawHere()
{
for (int count = 0; count < offset; count++)
System.out.print(' ');
System.out.println('*');
}
}
public interface ShapeInterface
{
public void setOffset(int noff); // set how many space from left
public int getOffset(); // returns offset
public void drawAt(int linnumber); // moves down equal to line number Ex. 5 = 5 down
public void drawHere(); // draws shape after moving left equal to offset
}
I'd ask to see your main method, but I don't have the reputation.
At a guess, I'd say maybe you are not actually instantiating objects of these classes in your main method, but trying to call the methods from them. If, for instance, you do this:
LeftArrow lArrow = new LeftArrow();
lArrow.drawHere();
it should work.
The method drawHere is declared as non-static. Instead of LeftArrow.drawHere() you should call
LeftArrow left = new LefArrow(a, b, c);
left.drawHere();
main is static. It needs to create instances of LeftArrow before it can use them. Something like this:
LeftArrow myArrow = new LeftArrow();
myArrow.drawHere();
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 8 years ago.
Improve this question
When I create a new array element, it gets stored into the array index, then the array index increments to the next.
However, I am getting a different result. The array element copies down to all previous array indexes.
import java.util.Scanner;
import java.io.*;
public class VectorOfContacts implements ProjTwo
{
private int size;
private int capacity;
private int incrementCapacity;
Contact[] contacts;
File file = new File("contacts.txt");
Scanner input = new Scanner(System.in);
public VectorOfContacts()
{
size = 0;
capacity = 10;
incrementCapacity = capacity;
contacts = new Contact[capacity];
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return capacity;
}
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
//public VectorOfContacts(int inCapacity)
//{
//inCapacity = 100;
//incrementCapacity = inCapacity;
//}
public void readInitialFromFile()
{
Contact c = new Contact();
String temp = null;
try{
Scanner input = new Scanner(file);
for (int i = 0 ; i < size; i++)
{
temp = input.nextLine();
String[] part = input.nextLine().split(":");
System.out.println(part);
String name = part[0];
long number = Long.parseLong(part[1]);
String comment = part[2];
c.setName(name);
c.setPhoneNumber(number);
c.setComment(comment);
contacts[i] = c;
contacts[size] = contacts[i];
}
input.close();
}catch(FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
}
public void writeFinalToFile()
{
try{
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < size; i++)
{
output.println(contacts[i]);
}
output.close();
}catch(FileNotFoundException a){
System.out.println("Something is wrong.");
System.exit(0);
}
System.exit(0);
}
public void addContact(Contact c)
{
addElement(c);
}
public void deleteContact(String nm)
{
System.out.println("Delete which name?");
nm = input.nextLine();
for(int i = 0; i < size; i++)
{
if(contacts[i].getName() == nm);
{
contacts[i] = contacts[i+1];
}
}
System.out.println("Deletion confirmed");
}
public void showByName(String nm)
{
nm = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (nm.startsWith(contacts[i].getName()))
{
System.out.println(contacts[i]);
}
}
}
public void showByPhoneNumber(long pN)
{
pN = input.nextLong();
for ( int i = 0; i < size; i++)
{
if (contacts[i].getPhoneNumber() == pN)
{
System.out.println(contacts[i]);
}
}
}
public void showByComment(String c)
{
c = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (c.startsWith(contacts[i].getComment()))
{
System.out.println(contacts[i]);
}
}
}
public boolean isFull()
{
if (size == capacity)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
public void addElement(Contact item)
{
if (isFull() == true)
incrementCapacity();
contacts[size] = item;
size++;
System.out.println("size" + size);
for (int i = 0; i < size; i++)
{
System.out.println(contacts[i]);
}
}
public void incrementCapacity()
{
Contact[] temp_contacts = new Contact[capacity + incrementCapacity];
for(int i = 0; i < size; i++)
{
temp_contacts[i] = contacts[i];
}
capacity = capacity + incrementCapacity;
contacts = temp_contacts;
}
}
These are the end results
size1
test:1234:1
size2
no:5555:2
no:5555:2
size3
jaja:1666:test
jaja:1666:test
jaja:1666:test
You print one object for all indexes, you need to use next:
for (int i = 0; i < size; i++){
System.out.println(contacts[i]);
}
You could improve a lof of things.
Don't expose everything as public
The class VectorOfContacts does a lot of things. You should split it into many classes.
Use the Java Framework (Array.copy(), ArrayList, ...)
Don't do if (true) return true else return false
Write tests
In readInitialFromFile you're creating the contact outside of the loop. So you reusing the same object of all contacts.
Those setters dont do anything, you missing an argument. But they shouldn't be public anyway so you don't need them.
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
isFull and isEmpty shouldn't be public and can be a lot shorter
private boolean isFull() {
return size == capacity;
}
private boolean isEmpty() {
return size == 0;
}
Please clean up your code first.