Java: cannot find symbol - java

in this class I'm making a catchFish method, it basically returns a random fish from the pond, the fish should be removed from the pond and returned from the method, If there are no fish then null will be returned
this is my code
import java.util.Random;
public class Pond {
private int MAX_FISH = 10;
private Fish[] fish = new Fish[MAX_FISH];
private int numFish;
public Pond (int numFish, Fish[] fish) {
this.numFish = numFish;
this.fish = fish;
}
public int getNumFish() {
return numFish;
}
boolean isFull(){
if (numFish < MAX_FISH) {
return false;
} else {
return true;
}
}
public String toString(){
return "Pond with " + numFish + " fish";
}
public void listFish() {
System.out.println("Pond with " + numFish + " as follows:");
for (int i = 0; i < numFish ; i++) {
Fish f = fish[i];
System.out.println("A " + f.getSize() + " cm " + f.getSpecies());
}
}
public void add(Fish f) {
if (isFull()) {
System.out.println("Sorry, the pond is full!");
} else {
numFish++;
fish[numFish-1] = f;
}
}
public Fish catchAFish() {
if (numFish == 0) {
System.out.println("Sorry, the pond is empty!");
return null;
} else {
Fish f = new Fish();
int r = (int)Math.random()*(numFish-1);
f = fish[r];
if (r == (numFish -1)) {
fish[r] = null;
} else {
fish[r] = fish[numFish-1];
}
numFish--;
return f;
}
}
}
and in catchAFish method the line
Fish f = new Fish(); gives an error:
java:55: cannot find symbol
symbol : constructor Fish()
location: class Fish
and I don't understand what I'm doing wrong?
EDIT:
fish class
public class Fish {
private String species;
private int size;
public Fish(int size, String species) {
this.size = size;
this.species = species;
}
public String toString() {
return " A " + size + " cm " + species;
}
public String getSpecies() {
return species;
}
public int getSize() {
return size;
}
}

Basically...Fish must have a non-empty constructor, requiring you to provide one or parameters when you create an instance of Fish.
Looking at the Fish code, the only constructor you provide is...
public Fish(int size, String species) {
There is no "default" constructor (which would allow you to use new Fish()).
But I'm not convinced that you actually need to create a new instance anyway, as you re-assign it almost immediately.
Fish f = new Fish();
int r = (int)Math.random()*(numFish-1);
// Overridden...
f = fish[r];
Instead, you could simply use...
int r = (int)Math.random()*(numFish-1);
Fish f = fish[r];

Java will create a default constructor, with no arguments, if you don't supply a constructor. So, if you cannot call a no-argument constructor, then you must have created a constructor that does take at least one argument.
Either supply the necessary arguments to call your existing Fish constructor, or create an explicit no-argument Fish constructor.

Since you haven't posted your Fish class I'm going to assume that it's the same as it was in your previous post.
You've defined a constructor for Fish with two parameters. Because you've supplied your own constructor Java will not supply the default no-args constructor. Either define a no-args constructor of your own or use your existing one.

Related

How to define a constructor to call it for each array?

I have class PERSON and BOUNCYHOUSE which are combined in main method class PARTNERLAB.
I have to add people to the bouncyhouse based on weight limit and if one bouncy house is full, move on to the next.
I get an error that looks like this:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor BouncyHouse() is undefined
at PartnerLab1.main(PartnerLab1.java:17)
How do I define BouncyHouse?
Here's my code:
PARTNER:
public class Person { //encapsulated class the has name and weight
private String name;
private int personWeight;
public Person(String name, int personWeight){ //two argument constructor thta takes in the name and weight and sets both attributes accordingly
this.name= name;
this.personWeight= personWeight;
}
public String getName() //get name
{
return this.name;
}
public int getWeight() //get weight
{
return this.personWeight;
}
public String getInfo(){ //return all info
return "Name: " + this.name +
"\n Person's weight: "+ this.personWeight;
}
BOUNCYHOUSE
import java.util.*;
public class BouncyHouse { //encapsulated class with weight limit and total current weight with all occupants in the bouncy house
private int weightLimit;
private int totalCurrentWeight;
private ArrayList <Person> occupants;
public BouncyHouse(int weightLimit, int totalCurrentWeight, ArrayList<Person> occupants){ //no arguments construction that sets the variable to a default value of 0
this.weightLimit= 0;
this.totalCurrentWeight= 0;
this.occupants = new ArrayList<>();
}
public void setWeightLimit(int weightLimit) //sets weight limit
{
this.weightLimit = weightLimit;
}
public void setTotalCurrentWeight(int totalCurrentWeigth) //sets total current wieght
{
this.totalCurrentWeight = totalCurrentWeigth;
}
public String getInfo() // return all the information about the bouncy house
{
StringBuilder personInfo = new StringBuilder();
for(Person person: occupants)
{
personInfo.append(person.getInfo()+",\n\t");
}
return "BouncyHouse: " +
"\nweightLimit=" + this.weightLimit +
"\ntotalWeight=" + this.totalCurrentWeight +
"\noccupants= " + personInfo.toString(); //can't do it in one sitting !
}
//NEXT: Add a person to the bouncy house
public boolean addPerson(Person person)
{
// check if weight exceeds the limit
if((person.getWeight()+totalCurrentWeight) <= weightLimit)
{
// add person to occupants list
this.occupants.add(person);
// update current total weigh
this.totalCurrentWeight += person.getWeight();
return true;
}
// else, return false
return false;
}
public Person[] addPerson(Person[] persons)
{
Person maxWeightPerson = null;
int maxWeight = 0;
for(int i =0; i < persons.length; i++)
{
// check if weight exceeds the limit
if (!addPerson(persons[i]))
{
if(persons[i].getWeight() < maxWeight)
{
// remove maxWeightPerson from house and add the current person
occupants.remove(maxWeightPerson);
totalCurrentWeight -= maxWeightPerson.getWeight();
// add person to occupants list
this.occupants.add(persons[i]);
maxWeight = 0;
// find next max weight guy
for (Person person : occupants)
{
if (person.getWeight() > maxWeight)
{
maxWeight = person.getWeight();
maxWeightPerson = person;
}
}
}
}
else
{
if(maxWeight < persons[i].getWeight())
{
maxWeight = persons[i].getWeight();
maxWeightPerson = persons[i];
}
}
}
return occupants.toArray(new Person[occupants.size()]);
}
}
PARTNERLAB
import java.util.*;
import java.util.Scanner;
public class PartnerLab1
{
public static void main(String[] args)
{
String choice, name;
int weight;
Scanner in = new Scanner(System.in);
BouncyHouse[] bouncyHouses = new BouncyHouse[2];
for (int i = 0; i < 2; i++)
{
bouncyHouses[i] = new BouncyHouse();
// set weight limits for bouncyHouse
bouncyHouses[i].setWeightLimit(250);
// add persons to houses
do
{
System.out.print("Add person to House " + (i + 1) + " (y/q): ");
choice = in.nextLine();
if (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter weight: ");
weight = Integer.parseInt(in.nextLine());
if (bouncyHouses[i].addPerson(new Person(name, weight)))
{
System.out.println("Person added");
} else
{
System.out.println("Person can't be added. Exceeds weight limit.");
}
}
} while (!choice.equalsIgnoreCase("q"));
}
// display people in houses
for (int i = 0; i < 2; i++)
{
System.out.println("People in House " + i + 1);
System.out.println(bouncyHouses[i].getInfo());
}
}
}
You have defined a parametrized constructor for your BouncyHouse class so you can't call a no-argument constructor without explicitly defining it in your class.
As per the code you have written in main class, You don't required parametrized constructor into BouncyHouse class. You can remove it or in case if you required some where else then add no-argument constructor in BouncyHouse class.

declaring an Object in another class

so I have the class Person, I then have another class called Building and I'm trying to create an object in building giving the person a default location and adding this into my toString method, so it displays when I run the program:
public class Person {
private Point p;
Person(Point np) {
this.p = np;
}
public String toString() {
return "Person at " + p.getX() + ", " + p.getY();
}
In the Building class I have declared private Person p then in setBuilding created the object with a new location then added p into my toString method, I think I got the right idea but whenever I run building it displays "null" and not "Person at " with the set X and Y coordinate which is in my person class. So ive definitely gone wrong somewhere any pointers in the right direction would be a great help thank you.
public class Building {
private int xSize = 10;
private int ySize = 10; // and y
private ArrayList<Room> allRooms;
private Person P;
Building (String first){
allRooms = new ArrayList<Room>();
setBuilding(first);
}
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
//defining the x and y coordinate
String[] buildingSize = Space[0].split(" ");
xSize = Integer.parseInt(buildingSize[0]);
ySize =Integer.parseInt(buildingSize[1]);
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
Person P = new Person (new Point(2,3));
}
public String toString() {
String s = "Building size " + xSize +","+ySize + P + '\n';
for (Room r : allRooms) { //for loop
s += r.toString();
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5"); // create
System.out.println(b.toString()); // and print
}
}
Please follow the java naming conventions.
private Person person;
is the correct naming convention.
Now in your setBuilding method,
public void setBuilding(String bS) {
.
.
this.person = new Person (new Point(2,3));
}
this will do.
Hope this helps. Cheers !!!

Finding max/min value using Comparable

I have an object class
public class Film implements Comparable<Film>
I'm using Eclipse and would like to know why Film is underlined in red with the error saying:
The type Film must implement the inherited abstract method Comparable<Film>.compareTo<Film>
And now to my main question:
How would I get the max/min user submitted film length and title?
My object class Film has getter and setter methods for the Title of the film and the Length of the film and a toString method. Following this article (#3) I created two more methods in my object class:
public int max(Film maxLength){
int compareLength = ((Film) maxLength).getLength();
return this.length - compareLength;
}
public int min(Film minLength){
int compareLength = ((Film) minLength).getLength();
return compareLength - this.length;
}
Could I use these to find and print max/min values of the user submitted film lengths?
If so, how?
If not, what is the proper way of doing this?
The test class is as follows:
import java.util.Scanner;
public class test {
public static void main (String[] args){
Film[] f = new Film[3];
Scanner input = new Scanner(System.in);
for (int i=0;i<3;i++){
f[i] = new Film();
System.out.println("Enter Film Length:");
f[i].setLength(input.nextInt());
input.nextLine();
System.out.println("Enter Title:");
f[i].setTitle(input.nextLine());
}
input.close();
for (int i = 0; i < 3; i++) {
System.out.println(f[i].toString());
}
}
}
The Film class implements Comparable<Film>. What this means is that you must implement a method called compareTo() in class Film that will provide an ordering for objects of this class.
#Override
public int compareTo(Film that) {
// Order by film length
return Integer.compare(this.length, that.length);
}
If you only need to sort the objects by film length you can just use Arrays.sort():
Film[] films = new Film[3];
// put the objects into the array
Arrays.sort(films);
Then films[0] will contain the film with the shortest length, while the last element will be the film with the longest length.
If you need to compare by other fields, such as film title, you can create a custom comparator:
class FilmTitleComparator implements Comparator<Film> {
public int compare(Film a, Film b) {
return Integer.compare(a.getTitle().length(), b.getTitle().length());
}
}
And pass it to Arrays.sort()
FilmTitleComparator titleComparator = new FilmTitleComparator();
Arrays.sort(films, titleComparator);
Then films[0] will contain the film with the shortest title, while the last element will be the film with the longest title.
For simplicity, I stubbed your Film class to show a trivial example of how to implement Comparable
public class Film implements Comparable<Film> {
int maxLength;
int minLength;
String title;
public Film() {
this.maxLength = 0;
this.minLength = 0;
this.title = "";
}
// implement this method to accomplish comparison
public int compareTo(Film f) {
int result = 0; // the result to compute.
if ( this.equals(f) ) {
result = 0; // these objects are actually equal
}
// compare using meaningful data
else if ( f != null) {
// check to see if this film is greater than the specified film
if ( this.getMaxLength() > f.getMaxLength() ) {
// this film is comparatively greater, return > 0
result = 1;
}
else if ( this.getMaxLength() == f.getMaxLength() ) {
// these two films are comparatively equal
result = 0;
}
else {
// this film is comparatively less than the specified film
result = -1;
}
// similarly, you could also check min, but there's really no reason to do that unless your implementation calls for it.
}
else {
throw new IllegalArgumentException("null Film object not allowed here...");
}
return result;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
if (maxLength != film.maxLength) return false;
if (minLength != film.minLength) return false;
if (!title.equals(film.title)) return false;
return true;
}
#Override
public int hashCode() {
int result = maxLength;
result = 31 * result + minLength;
result = 31 * result + title.hashCode();
return result;
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public int getMinLength() {
return minLength;
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
To fix your test to actually use such an implementation (it doesn't really test anything...), you could do:
import java.util.Scanner;
public class test {
public static void main (String[] args){
Film lastFilm = null; // arbitrary reference to film
Film[] f = new Film[3];
Scanner input = new Scanner(System.in);
for (int i=0;i<3;i++){
f[i] = new Film();
System.out.println("Enter Film Length:");
f[i].setLength(input.nextInt());
input.nextLine();
System.out.println("Enter Title:");
f[i].setTitle(input.nextLine());
}
input.close();
for (int i = 0; i < 3; i++) {
if ( lastFilm != null ) {
// compare the films to test. current to last film
if ( f[i].compareTo(lastFilm) > 0 ) {
System.out.println(f[i].getTitle() + " is greater than " + lastFilm.getTitle()");
}
else if ( f[i].compareTo(lastFilm) < 0 ) {
System.out.println(f[i].getTitle() + " is less than " + lastFilm.getTitle()");
}
else {
System.out.println(f[i].getTitle() + " is equal to " + lastFilm.getTitle()");
}
}
System.out.println(f[i].toString());
lastFilm = f[i];
}
}
}
Something like this can get you started... good luck
Another solution would be to implement Comparable<Film>:
#Override
public int compareTo(Film that) {
return this.length - that.length;
}
And use org.apache.commons.lang3.ObjectUtils#min or org.apache.commons.lang3.ObjectUtils#max like:
Film min = ObjectUtils.min(film1, film2);
Film max = ObjectUtils.max(film1, film2);

ArrayList<superclass> but use ArrayList<subclass>.methodofsubclass

Im having a class Woning (house) and a subclass KoopWoning (buyable House) and a subclass HuurWoning (rentable House). KoopWoning and Huurwoning extend Woning. HuurWoning is just a Woning, whereas KoopWoning has an extra variable energylevel. KoopWoning has also a function getEnergylevel, which returns the energylevel of the KoopWoning. I also have a class Portefeuille which has an arraylist of Woningen.
Im reading all Woningen in a Portefeuille from a textfile. In a 5th class, I want to be able to sort the ArrayList of Woningen of Portefeuille (from the textfile). I have a function woningenTot(int maxprijs) which returns an ArrayList with all the Woningen that fullfil the requirement (having a price below maxprijs). These Woningen I want to print on the screen.
The problem is as follows:
It can be possible that there is also a KoopWoning in the file. In that case I also want to be able to sort on energylevel. However, I can't sort on the energylevels. I can't call the function getEnergylevel because it's an ArrayList, and Woning doesn't contain the function getEnergylevel.
So how can I solve this? If it's too vague, I could include the code, however it's quite big :O
Any help is appreciated; i have spent a couple of hours on this program, from which at least 1.5 hours on this problem alone :(
EDIT: Here is the code for class KoopWoning
public class KoopWoning extends Woning implements EnergiepeilWoning {
private char energiepeil;
public KoopWoning (Adres adres, int kamers, int vraagPrijs, char energiepeil) {
super(adres, kamers, vraagPrijs);
this.energiepeil = energiepeil;
}
public char getEnergiepeil () {
return energiepeil;
}
public boolean compareEnergiepeil (Object other) {
boolean res = false;
if (other instanceof KoopWoning) {
KoopWoning that = (KoopWoning) other;
res = (this.getEnergiepeil() == that.getEnergiepeil());
}
return res;
}
public String toString () {
String res = adres + ", " + kamers + " kamers, prijs " + prijs + ", energiepeil " + energiepeil;
return res;
}
And here is the code for class Woning
public class Woning {
protected int kamers;
protected int prijs;
protected Adres adres;
protected String tag;
public Woning (Adres adres, int kamers, int prijs) {
this.adres = adres;
this.kamers = kamers;
this.prijs = prijs;
}
public String toString () {
String res = adres + ", " + kamers + " kamers, prijs " + prijs;
return res;
}
public void setTag (String tag) {
this.tag = tag;
}
public String getTag () {
return tag;
}
public boolean kostHooguit (int maxprijs) {
return (prijs <= maxprijs);
}
public boolean equals (Object other) {
boolean res = false;
if (other instanceof Woning) {
Woning that = (Woning) other;
if (this.adres.equals(that.adres))
res = true;
}
return res;
}
public static Woning read (Scanner sc) {
try {
Adres adress = Adres.read(sc);
int kamer = sc.nextInt();
sc.next();
sc.next();
int prijs = sc.nextInt();
String check = sc.next();
if (check.equals("energiepeil")) {
char peil = sc.next().charAt(0);
KoopWoning kwoning = new KoopWoning (adress, kamer, prijs, peil);
return kwoning;
}
else {
Woning woning = new Woning (adress, kamer, prijs);
return woning;
}
}
catch (Exception e) {
System.out.println("Woning: Exception is caught");
System.out.println(e.getMessage());
Adres adress = new Adres ("", "", "", "");
Woning woning = new Woning (adress, 0, 0);
return woning;
}
}
}
And lastly, the code for the class Portefeuille
public class Portefeuille {
private ArrayList<Woning> woninglijst;
public Portefeuille () {
woninglijst = new ArrayList<Woning>();
}
public void voegToe (Woning woning) {
if (!woninglijst.contains(woning))
woninglijst.add(woning);
}
public ArrayList<Woning> woningenTot (int maxprijs) {
ArrayList<Woning> woninglijst2 = new ArrayList<Woning>();
for (int i = 0; i < woninglijst.size(); i++) {
if(woninglijst.get(i).kostHooguit(maxprijs))
woninglijst2.add(woninglijst.get(i));
}
return woninglijst2;
}
public String toStringExt () {
String res = "[";
for (int i = 0; i < woninglijst.size(); i++)
res = res + woninglijst.get(i).toString() + "; ";
if (woninglijst.size() != 0)
res = res.substring (0, res.length() - 2);
res = res + "]";
return res;
}
public String toString () {
String res = "";
for (int i = 0; i < woninglijst.size(); i++)
res = woninglijst.get(i).toString2();
return res;
}
public boolean equals (Object other) {
boolean res = false;
if (other instanceof Portefeuille) {
Portefeuille that = (Portefeuille) other;
if (this.woninglijst.size() == that.woninglijst.size()) {
int i = 0;
while (i < this.woninglijst.size() && this.woninglijst.get(i).equals(that.woninglijst.get(i)))
i = i + 1;
res = (i == this.woninglijst.size());
}
}
return res;
}
public static Portefeuille read (String infile) {
try {
Scanner sc = new Scanner (new File(infile));
ArrayList<Woning> wlijst = new ArrayList<Woning>();
Portefeuille p = new Portefeuille();
int woningen = sc.nextInt();
int i = 0;
while (i < woningen) {
sc.nextLine();
String tag = sc.nextLine();
wlijst.add(Woning.read(sc));
p.voegToe(wlijst.get(i));
i++;
}
sc.close();
return p;
}
catch (Exception e) {
System.out.println("Portefeuille: Exception is caught");
Portefeuille p = new Portefeuille();
return p;
}
}
}
EDIT
I fixed it myself. Thanks for answering you all :)
You could define, on the top-level class, a method like getSortableValue(), and implement it to return a default field (you didn't mention the field you need to sort on for Woningen). In the KoopWoning you override this method to return the energyLevel instead. Then you always sort on the value returned by getSortableValue().
You can let the them implement Comparable, so like Woning implements Comparable<Woning>. This will let you implement the (required) method:
#override
public int compareTo(Woning other) {
int result = Integer.compareto(maxPrijs, other.maxPrijs);
if (result != 0) return result;
result = Integer.compareto(someField, other.someField);
if (result != 0) return result;
// etc...
return 0;
}
The subclass KoopWoning extends Woning implements Comparable<KoopWoning> can have a method like this:
#override
public int compareTo(KoopWoning other) {
int result = Integer.compareto(energylevel, other.energylevel);
if (result != 0) return result;
return super.compareTo(other);
}
Then all you need to do is load all the Woning instances in a list and execute
Collections.sort(list);
Having subclasses inherit Comparable is optional, so HuurWoning will just sort like Woning.
You could define a Comparator on Woning that determines the relative ordering of two Woning. You could do this either by having a method that looks at the actual types of the two arguments and then acts appropriately, or, better, by having an overrideable method of Woning that returns some value that you can use for sorting purposes.
If, for instance, you decide that anything with an energy level should come after anything without one, then you can have KoopWoning return something with the energy level in the high order bits of a long, so that it always comes out higher than anything without one (essentially you'd be setting a default energy level of zero).
Then, you can use
Collections.sort(arrayList, myComparator);
to sort the list based on the Comparator you've created.
There are some nice classes in the Guava library that help with Comparator building on multiple keys, but if your case is fairly simple, you probably won't need them.

implementing a method from one class to another?

I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:
str= str + seats[i][j].toString();
I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?
Airplane class:
public class Airplane
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;
public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}
}
Seat Class:
public class Seat
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;
public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}
public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}
In Seat.toString you should print a " " not "".
You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.
seats seems to does not have Seat's instance.
Add this code :
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
seats[i][j] = new Seat();
}
}
below this :
seats = new Seat[FC_ROWS][ECONOMY_COLS];
I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.

Categories