Java: method not working - java

I am creating a program that simulates some people catching fish in a lake, I already created classes for Fish and Pond and I was working on the Fisher class and a method is not working and I'll show the code (I'm new to programming so I'm not sure if I am providing enough information)
public class Fisher {
public static int LIMIT = 3;
private String name;
private Fish[] fishCaught = new Fish[LIMIT];
private int numFishCaught;
private int keepSize;
public Fisher(String name, Fish[] fishCaught, int numFishCaught, int keepSize) {
this.name = name;
this.fishCaught = fishCaught;
this.numFishCaught = numFishCaught;
this.keepSize = keepSize;
}
public String getName() {
return name;
}
public Fish[] getFishCaught(){
return fishCaught;
}
public int getNumFishCaught() {
return numFishCaught;
}
public int getKeepSize() {
return keepSize;
}
public String toString() {
return (name + " with " + numFishCaught + " fish");
}
public void keep(Fish f) {
if (numFishCaught == LIMIT) {
} else {
numFishCaught++;
fishCaught[numFishCaught-1] = f;
}
}
boolean likes(Fish f) {
if ((f.getSize() >= keepSize) && !(f.getSpecies().equalsIgnoreCase("Sunfish"))) {
return true;
}
return false;
}
public void listFish(){
System.out.println(name + " with " + numFishCaught + " as follows: ");
for (int i = 0; i<numFishCaught; i++){
Fish f = new fish[i];
System.out.println("A " + f.getSize() + " cm " + f.getFishCaught());
}
}
}
the problem is the listFish() method, it's supposed to return something like this:
Bob with 2 fish as follows:
A 4 cm Pike
A 15 cm Bass
but it's not working it gives me "incompatible types" and "cannot find symbol" errors??
(just to make your life easier i'll include the Fish class too)
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;
}
}
Error: /Users/halahalhomoud/Fisher.java:57: incompatible types
found : Fish[]
required: Fish
File: /Users/halahalhomoud/Fisher.java [line: 58]
Error: /Users/halahalhomoud/Fisher.java:58: cannot find symbol
EDIT:
show you how? I used it in the Pond class and it worked fine but I don't get why it's not working here.

You want the fish that are caught by a Fisher. Now, you have that information in the array you can retrieve with getFishCaught.
Now look what you try to do instead:
Fish f = new fish[i];
System.out.println("A " + f.getSize() + " cm " + f.getFishCaught());
In the first line, you try to make a new array of fish, but it is, of course Fish (fish is the symbol that couldn't get resolved.). Then you try to assign the array reference to a single Fish f. But an array of Fish is not the same as a Fish. For example, you can eat a Fish, but not a Fish container, you know.
What you probably want is this:
Fish f = (getFishCaught())[i]; // get the i-th Fish caught
System.out.println("A " + f.getSize() + " cm " + f.getXXX());
where getXXX is a method of Fish that returns the Fishs species. (Since you didn't show the FIsh class, I can't know the exact name of this getter).

Fish f = new fish[i];
should be:
Fish f = fishCaught[i];
Complete Method
public void listFish(){
System.out.println(name + " with " + numFishCaught + " as follows: ");
for (int i = 0; i<numFishCaught; i++){
if(fishCaught[i] != null){
Fish f = fishCaught[i];
System.out.println("A " + f.getSize() + " cm " + f.getSpecies());
}
}
}

Related

java - Function in class

I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.

Own Object can't be added to ArrayList. instead all objects are overwritten

I try to determine the error since yesterday, but did not find him. All I know is where he must be placed approximately. But now to the topic.
For my app I have created a separate class with the name Player. Now if I make an ArrayList with this class, a newly added object overwrites all existing objects. So:
ArrayList empty -> Player is stored in ArrayList
ArrayList already contains a Player -> ArrayList now contains the newest Player instance two times
etc.
Here is my code corresponding to:
Player Object
public Player(String n, int m, int t) {
name = n;
money = m;
tip = t;
}
public String getName() {
return this.name;
}
public int getMoney() {
return this.money;
}
public int getTip() {
return this.tip;
}
public String toString() {
return this.name + "\n Tipp: " + this.tip + " | Einsatz: " + this.getMoney() + " ,- €";
}
Creating the ArrayList
public void addPlayertoEvent(String name, int money, int tip) {
Player p = new Player(name, money, tip);
playerList.add(p);
playerListString.add(p.toString());
lvPlayers.setAdapter(null);
ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(AddEventActivity.this, R.layout.list_items, playerListString);
lvPlayers.setVisibility(View.VISIBLE);
lvPlayers.setAdapter(playerAdapter);
etTip.setText("");
etName.setText("");
for(int i = 0; i < playerList.size(); ++i) {
Log.e("AL", "" + playerList.get(i).getName() + " " + playerList.get(i).getMoney() + " " + playerList.get(i).getTip());
}
}

How to display an istanceof an object in an arraylist? (Polymorphism)

I am trying to display all of the elements in the ArrayList plantList.
My main program will add, delete, search, filter, and display all of the plants of four different child classes. Everything "seems" to be working except when I display.
~I will only including portions of my code that are relevant to the questions.
A little background: I am a student and this is my first time working with inheritance/polymorphism.
1)How do I distinguish between the different objects since they all have different parameters, at the time of displaying?
2) Any suggestions on how to improve the performance/logic of what I'm doing? A little explanation would be great.
//Parent class
public class Plant{
private String name;
private String id;
private String color;
public Plant(String name, String id, String color){
this.name = name;
this.id = id;
this.color = color;
}
public String getName(){
return this.name;
}
public void setName(String name){
name = this.name;
}
public String getId(){
return this.id;
}
public void setId(String id){
id = this.id;
}
public String getColor(){
return this.color;
}
public void setColor(String color){
color = this.color;
}
}
//one of several child classes
public class Flower extends Plant{
private boolean thorns;
private boolean smell;
public Flower(String name, String id, String color, boolean blnThorns, boolean blnSmell){
super(name, id, color);
thorns = blnThorns;
smell = blnSmell;
}
public boolean isThorns(){
return thorns;
}
public void setThorns(boolean blnThorns){
thorns = blnThorns;
}
public boolean isSmell(){
return smell;
}
public void setSmell(boolean blnSmell){
smell = blnSmell;
}
}
// portion of the main driver
ArrayList<Plant> plantList = new ArrayList<Plant>();
//adding a flower to the plantList
System.out.println("\nEnter the name of the flower to add: ");
name = add.nextLine();
System.out.println("\nEnter the ID code: ");
id = add.nextLine();
System.out.println("\nEnter the color: ");
color = add.nextLine();
System.out.println("\nAre there thorns present? (True/False) ");
blnThorns = add.nextBoolean();
System.out.println("\nDoes the flower smell? (True/False) ");
blnSmell = add.nextBoolean();
plantList.add(new Flower(name, id, color, blnThorns, blnSmell));
System.out.println("Flower inserted.");
System.out.println();
break;
//displaying all plants
for( int i = 0; i < plantList.size(); i++){
System. out.println("\t" + (i+1) + ":");
System.out.print("\n\tName: " + plantList.get(i).getName());
System.out.print("\n\tName: " + plantList.get(i).getId());
System.out.print("\n\tColor: " + plantList.get(i).getColor());
if(plantList instanceof Flower){ // HERE I am not sure what I'm doing or how to do it
System.out.print("\n\tThorns presence: " + plantList.get(i).isThorns()); /* this is an example of what is not working properly */
System.out.print("\n\tSmell presence: " + plantList.get(i).isSmell()); /* this is an example of what is not working properly*/
System.out.println("\n");
}
}
If by "display" you mean "print some sort of string to the console or other output", then the answer is fairly simple: there's no need to use instanceof at all. All you need to do is override the toString method in each different class that you want to be displayable, then when you want to display an object (even if you don't know exactly what type it is), just call toString on it and print the result. Polymorphism will do the job of picking which toString method implementation to call.
Here's how it would look in your specific example.
In the Plant class:
#Override
public String toString() {
return "\n\tName: " + getName()
+ "\n\tName: " + getId()
+ "\n\tColor: " + getColor();
}
Then, in the Flower class:
#Override
public String toString() {
return super.toString()
+ "\n\tThorns presence: " + isThorns()
+ "\n\tSmell presence: " + isSmell();
}
Finally, to display all plants:
for (Plant plant : plantList) {
System.out.println(plant);
}
Note that toString is called automatically when you pass any Object to System.out.println.
You were really close. You just needed to check against the element of the list, not the list itself, when you did the instanceof check. Then, if it is in fact an instance of Flower, then you need to cast the list element to a Flower and make the method calls from there.
Like this:
for(int i = 0; i < plantList.size(); i++){
System.out.println("\t" + (i+1) + ":");
System.out.print("\n\tName: " + plantList.get(i).getName());
System.out.print("\n\tName: " + plantList.get(i).getId());
System.out.print("\n\tColor: " + plantList.get(i).getColor());
if (plantList.get(i) instanceof Flower) {
Flower flower = (Flower)plantList.get(i);
System.out.print("\n\tThorns presence: " + flower.isThorns());
System.out.print("\n\tSmell presence: " + flower.isSmell());
System.out.println("\n");
}
}

How to access arraylist from another class for which the main purpose of the class is not the arraylist

I've read pages and pages of stackoverflow to try to fix my problem and reworked my coding many times to no avail. I wish I could simplify my question, but I'm not entirely sure I know what it going wrong in my code.
I am in the stages of creating a game for a class I'm taking. Thus far, the code involves a parent class for creatures, and child classes of creature types (animal, NPC, etc), which are loaded rooms, another class. I have created a SAXParser to parse an xml file that contains the details of each creature and room, so as to fill out the game with rooms and creatures in each room. My check for the current assignment is to print out the contents of a given room when the user gives the name of the room it would like to see. The rooms are held in the roomArrayList. I have created a main class that holds the responsibility of processing user input.
The rooms ARE filled with the right things. When I set the "EndElement" method in the parser to print the contents of the room that was just created, the output is correct.
However, when I try to print the contents of one of the rooms per the user's request from the main class using the roomArrayList, I get exceptions. I imported the array into the main class with a get method, as you'll see below. I can tell something is wrong because when I print the size of the imported array, it prints zero.
I won't bother to include the creature parent class and the subclasses.
Here is the MyHandler class:
public class MyHandler extends DefaultHandler {
private List<Room> roomList = null;
private Room r;
private PC pc;
private String south, north, west, east;
ArrayList<Room> roomArrayList = new ArrayList<Room>();
public ArrayList<Room> getArrayList() {
return roomArrayList;
}
public int checkRoomMatch(String match) {
int a = -1;
for (int i = 0; i < roomArrayList.size(); i++) {
if (roomArrayList.get(i).RoomName.equals(match)) {
a = i;
}
}
return a;
}
public void startDocument() {
System.out.println("Document parsing started.");
}
#Override
public void startElement(String uri, String localName, String
qName, Attributes attributes) {
if (qName.equals("room")) {
r = new Room(attributes.getValue("name"));
r.setDescription(attributes.getValue("description"));
r.setState(attributes.getValue("state"));
north = attributes.getValue("north");
west = attributes.getValue("west");
east = attributes.getValue("east");
south = attributes.getValue("south");
r.setNeighbor(south, north, east, west, roomArrayList);
roomArrayList.add(r);
}
else if (qName.equals("animal")) {
Animal animal = new Animal
(attributes.getValue("name"), attributes.getValue("description"),
r, qName);
r.addCreature(animal);
}
else if (qName.equals("NPC")) {
NPC npc = new NPC(attributes.getValue("name"),
attributes.getValue("description"), r, qName);
r.addCreature(npc);
}
else if (qName.equals("PC")) {
pc = new PC(attributes.getValue("name"),
attributes.getValue("description"), r, qName);
r.addCreature(pc);
}
}
public void endElement(String uri,
String localName,
String qName) {
if (qName.equals("room")) {
System.out.println(r.toString());
}
}
public void endDocument() {
System.out.println("Document parsing ended.");
}
}
Here is my Room class:
public class Room {
Creature[] CreatureArray = new Creature[10];
String RoomName;
private int CreatureCount = 0;
String description;
String currentState;
final String Dirty = "dirty";
final String HalfDirty = "half-dirty";
final String Clean = "clean";
// 0 is north, 1 is east, 2 is south, 3 is west
private Room[] roomArray = new Room[4];
public Room(String name) {
RoomName = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setState(String state) {
this.currentState = state;
}
public String getName() {
return RoomName;
}
public String toString() {
String roomInfo = "";
roomInfo += "This room is called" + RoomName + "." + "\n";
roomInfo += "The following animals are in this room: ";
for (int x = 0; x < CreatureCount; x++) {
roomInfo += CreatureArray[x].toString();
if (x < CreatureCount - 1) {
}
}
roomInfo += "\n" + "The description for room " + RoomName + " is:
" + description + ". " + "\n ";
roomInfo += "The current state of room " + RoomName + " is " +
currentState + "." + "\n";
roomInfo += "Room " + RoomName + " is positioned with room " +
"roomArray[0]" + " to the north, room "
+ "roomArray[1]" + " to the east, room " + "roomArray[2]"
+ " to the south and room "
+ "roomArray[3]" + " to the west." + "\n";
return roomInfo;
}
public void addCreature(Creature a) {
if (CreatureCount < 10) {
CreatureArray[CreatureCount] = a;
CreatureCount++;
}
else {
System.out.println("This room is full.");
}
}
public void setNeighbor(String south, String north, String east,
String west, ArrayList<Room> roomArrayList) {
if (roomArrayList.size() >= 1) {
for (int i = 0; i < roomArrayList.size(); i++) {
if (roomArrayList.get(i).RoomName.equals(north)) {
roomArray[0] = roomArrayList.get(i);
roomArrayList.get(i).roomArray[2] = this;
continue;
}
if (roomArrayList.get(i).RoomName.equals(south)) {
roomArray[2] = roomArrayList.get(i);
roomArrayList.get(i).roomArray[0] = this;
continue;
}
if (roomArrayList.get(i).RoomName.equals(east)) {
roomArray[1] = roomArrayList.get(i);
roomArrayList.get(i).roomArray[3] = this;
continue;
}
if (roomArrayList.get(i).RoomName.equals(west)) {
roomArray[3] = roomArrayList.get(i);
roomArrayList.get(i).roomArray[1] = this;
continue;
}
}
}
}
}
And here is the main method, where user inputs are processed. I've commented out the command to print the size of the imported array. But do recall that when that line is ran, the output it zero. The println command below it is the function that is supposed to work that should print the contents of the selected room.
public class Main {
public static void main(String[] a) throws Exception {
File f;
Scanner fs = null;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a file name:");
String fileName = kb.nextLine();
f = new File(fileName);
if (!f.exists()) {
System.out.println("File not found. Please try again.");
System.out.println("Enter a file name:");
}
SAXParserFactory factory = SAXParserFactory.newInstance();
MyHandler handler = new MyHandler();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(fileName, new MyHandler());
System.out.println("Enter the name of a room for which you would " +
"like to see the contents.");
String selectedRoom = kb.nextLine();
ArrayList<Room> roomArrayList = handler.getArrayList();
int roomIndex = handler.checkRoomMatch(selectedRoom);
while (roomIndex == -1) {
System.out.println("No such room existed in the input file.");
System.out.println("Enter the name of a room for which you " +
"would like to see the contents.");
selectedRoom = kb.nextLine();
roomIndex = handler.checkRoomMatch(selectedRoom);
}
// System.out.println(roomArrayList.size());
System.out.println(roomArrayList.get(roomIndex).toString());
}
}
I hope I've created this question correctly. This is my first time making a question because I really feel I've exhausted my resources.
tl;dr -- Why is my filled roomArrayList not being imported into my main method?
You are passing a new instance of MyHandler to Parser where in that instance your array list will be populated and not in you existing handler instance and hence it remains empty.
So instead of passing new hanlder use existing handler like:
saxParser.parse(fileName, new MyHandler());
Use:
saxParser.parse(fileName, handler);//now handler will be having array list populated with rooms and you could use it further.

Cannot find symbol. Is looking in Superclass instead of subclass

I have a program that interprets and sorts data for a car dealer, and there is an error when trying to retrieve the color of the cars stored in an array.
Here is the main class and its sub class.
class Car
{
protected String model;
protected int price;
protected int year;
public Car(String m, int y, int p)
{
model = m;
price = p;
year = y;
}
}
class NewCar extends Car
{
protected String color;
public NewCar(String m, int y, int p, String c)
{
super(m, y, p);
color = c;
}
public String toString()
{
return "Model: " + model + "\n"
+ "Year: " + year + "\n"
+ "Price: $" + price + "\n"
+ "Color: " + color + "\n"
+ "Selling Price: " + price + "\n\n";
}
}
Here is another class in which the error occurs, at if(cars[z].color.equals(shade)).
The program cannot find variable color in class Car.
class CarDealerShip
{
public String printAllCarsOfColor(String shade)
{
String s = "";
for(int z = 0; z < i; z++)
{
if(cars[z].color.equals(shade))
{
s += "Car " + (z + 1) + "\n" + cars[z].toString();
}
}
return s;
}
How can I have the program look in class NewCar where variable color exists?
Your array cars appears to be of type Car[]. With a reference variable of Car after you have referenced the array element, there is no way to tell if it refers to a Car, a NewCar, or another subclass of Car.
It looks like you expect cars[z] to have the attribute color, so perhaps cars should be of type NewCar[] instead of Car[].
Another option is to move the attribute color to the superclass Car so any Car can have a color.
When using protected access the field will be available in classes that are within the same package or are a subclass of the base class. I'm assuming the class CarDealerShip which accesses the color field is not within the same package or does not extend Car.
The color is protected in NewCar. You can access protected variable only in sub classes. You need to move color to Car and add a public String getColor() method in your Car to make it available for the classes which are not part of the Car inheritance hierarchy.
public String getColor() {
return color;
}
and then your condition would be
if(cars[z].getColor().equals(shade))
Update
In case you want color to be in NewCar, you should add the public String getColor(); method in NewCar and your cars[] should be NewCar[], something like,
NewCar cars[] = new NewCar[arraySize]();
with this you will loose the inheritance capabilities, you can not use Car cars[] = new NewCar[arraySize] anymore.
If it's a requirement that color has to be in class NewCar you could use the instanceof operator and then cast it:
class CarDealerShip
{
public String printAllCarsOfColor(String shade)
{
String s = "";
for(int z = 0; z < i; z++)
{
if (cars[z] instanceof NewCar)
{
NewCar nc = (NewCar)cars[z];
if (nc.color.equals(shade))
{
s += "Car " + (z + 1) + "\n" + nc.toString();
}
}
}
return s;
}
}
You actually skip every Car that it not a NewCar and use only those that are an instance of the class NewCar.

Categories

Resources