Making an array of objects - java

I have made a class called Fish:
public class Fish {
private String species;
private int size;
//Constructor
public Fish(int x, String s) {
size = x;
species = s;
}
public String getSpecies() { return species; }
public int getSize() { return size; }
public String toString() {
return String.format("A %dcm %s", size, species);
}
}
And I have also started to make a class called pond that is meant to have an attribute called 'fish' that holds an array of Fish objects. I am unsure of how to do this. Here is my attempt so far. I am
public class Pond {
private int capacity;
private Object[] fish; //This is what I am trying to initialize. list of Fish.
private int numFish;
//Capacity Constructor
public Pond(int n, int c) {
n = numFish;
c = capacity;
}
public int getNumFish() { return numFish; }
public boolean isFull() {
boolean isFull = false;
if (numFish >= capacity) {
isFull = true;
}
else {
isFull = false;
}
return isFull;
}
public String toString() {
return String.format("Pond with %d fish", numFish);
}
public void add(Fish aFish) {
if (numFish <= capacity) {
numFish += 1;
fish.add Fish;
}
else {
numFish += 0;
}
}
}

Change this:
private Object[] fish;
as follows:
private Fish[] fish;
i.e. these are fishes and not just any
kinds of objects (they not mammals e.g.).

Following is invalid -
fish.add aFish;
with arrays you do
fish[numFish] = aFish; //increment numFish after this
You also need to initialize your array
fish = new Fish[capacity];
in your constructor.

In the Pond constructor you're assigning private fields to constructor arguments. I think it should be the other way around:
public Pond(final int n, final int c) {
numFish = n;
capacity = c;
}
A side note: declaring Pond constructor arguments final would prevent these kind of error at compile time.
Also, if you want to expand fish array at runtime then array is not the best choice of the container type. ArrayList<Fish> is a better choice as it can expand at runtime.

You need to use ArrayList instead of Array since an ArrayList can grow according to requirements.
Take a look at this code.Should help you:
public class Fish {
String name;
public Fish(String name) {
this.name=name;
}
public String toString() {
return name;
}
}
And then:
import java.util.*;
public class Pond {
ArrayList<Fish> fishInPond = new ArrayList<>();
public void addFish(Fish e) {
fishInPond.add(e);
}
public void showFishes() {
for (int i= 0; i<fishInPond.size();i++) {
fishInPond.get(i);
}
System.out.println("Fishes in my pond: " + fishInPond);
}
public static void main(String[]args) {
Pond myPond = new Pond();
myPond.addFish(new Fish("Tilapia"));
myPond.addFish(new Fish("cat fish"));
myPond.showFishes();
}
}

Related

Creating a Pokémon class in Java

I have a Java project that requires me to have two classes called: Pokemon.java and Move.java so I can add new Pokemon and their moves. I’ve already written all of the methods that were required for the project but I’m having issues storing and modifying the moves, specifically the forgetMove method in the Pokemon class.
Here’s the code for Pokemon.java:
public class Pokemon
{
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private Move move;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(Move.getNumOfMoves() < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move move)
{
if(canLearnMoreMoves())
{
this.move = move;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
if(Move.equals(other))
{
move -= other;
}
}
public String toString()
{
return name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
}
and here is the code for Move.java:
public class Move
{
// Copy over your Move class into here
private static final int MAX_DAMAGE = 25;
private static String name;
private static int damage;
public static int numMoves;
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
numMoves++;
}
public static String getName()
{
return name;
}
public static int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public static boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Here is the code for PokemonTester.java:
public class PokemonTester extends ConsoleProgram
{
public void run()
{
Pokemon p1 = new Pokemon("Charrizard", 100);
Move m1 = new Move("Flamethrower", 90);
System.out.println(p1);
System.out.println(m1);
}
}
This seems like it might be homework so I won't give you a full implementation.
If you are simply filling out the methods required for the Pokemon and Move class, I would start by reconsidering the way you are storing moves.
The getNumOfMoves provides a hint that your Pokemon class should store more than one move, a common way to do this is with arrays or lists.
If you have stored your moves in a list, the forgetMove function may look like this:
public void forgetMove(Move other){
moves.remove(other);
}

unable to assign array list to an array of an Object (Java)

So i am trying to make a deal or no deal game the game is not finished yet but the biggest issue i am having is that when i am trying to assign an array list to a array of type cases it seems like it isn't getting assigned.
I tried to debug and after shuffle the output is correct but i am unable to assign the result to the case array so that i can use it in game
Below are my 3 classes upon assigning the outcome i am getting is
The line i am talking about is the method available cases
public class Case {
private int value = 0;
private String face;
/*
* Constructor for type Case
*/
public Case(int value)
{
this.value = value;
}
/*
* Getter and setter methods for instance data
*/
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
}
public class Player {
private String name;
private int age;
private boolean canPlay = false;
private int money = 0;
/*
* Constructor for type Player
*/
public Player(String name, int age) {
super();
this.name = name;
this.age = age;
}
/*
* Getter and Setter methods for all instance Data
*/
public Player(boolean canPlay)
{
this.canPlay = canPlay;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public boolean isCanPlay() {
return canPlay;
}
public void setCanPlay(boolean canPlay) {
this.canPlay = canPlay;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* This method will check if the person playing is at least 18 years old or not
*/
public void checkAge()
{
if(age >= 18)
{
canPlay = true;
System.out.println("Seems like you are old enough to play!");
System.out.println("Let's get started");
}
else
{
canPlay = false;
System.out.println("OH NO! you aren't old enough sadly we won't be able to continue");
}
}
public String toString() {
return "Today's player is "+name+" who is "+age+" old";
}
public static void setupPlayer()throws InputMismatchException
{
String playerName;
int playerAge;
System.out.println("Welcome to the Deal or No Deal game!");
System.out.println("Please state your name:");
Scanner name = new Scanner(System.in);
playerName = name.nextLine();
System.out.println("Welcome "+playerName+" how old are you?");
Scanner age = new Scanner(System.in);
playerAge = age.nextInt();
Player gamePlayer = new Player(playerName, playerAge);
}
public static void Rules()
{
System.out.println("Below listed are the Game Rules\n");
System.out.println("-There are 12 Cases in the game");
System.out.println("-Each case contains a amount of money and you will be "
+ "offered these Cases 1 at a time");
System.out.println("-Upon picking a Case the game will end and you will have a "
+ "chance to walk away with that case");
System.out.println("-If No cases are picked you will get 2 option, to walk away"
+ " with the last Case or take the bankers offer");
System.out.println("-To accept the case type \"Y\" ,to decline it type \"N\"");
}
}
public class SetUpCases {
private Case[] cases = new Case[12];
/*
* This method initializes each object type with an amount which will be the Money in each Case
*/
public void settingUpCases()
{
ArrayList<Integer> myCase= new ArrayList<Integer>();
myCase.add(new Integer(1));
myCase.add(new Integer(50));
myCase.add(new Integer(100));
myCase.add(new Integer(250));
myCase.add(new Integer(500));
myCase.add(new Integer(1000));
myCase.add(new Integer(2500));
myCase.add(new Integer(5000));
myCase.add(new Integer(10000));
myCase.add(new Integer(25000));
myCase.add(new Integer(50000));
myCase.add(new Integer(100000));
/*
* The Shuffle changes which index has what value so game results are different each time played!
*/
Collections.shuffle(myCase);
for(int i = 0; i < cases.length; i++)
{
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(cases[i]);
}
}
/*
* Shows which Cases are still available
*/
public void availableCases()
{
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k]);
}
}
public void startGame()
{
settingUpCases();
}
}
You are printing case object instead of its value.. use getValue (or getFace) method to print the value (or face). For example
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k].getValue());
}
If you want to print both value and face, the best way will be to override the toString method and print these variables there.
The reason you are getting those weird values is not because the assignments aren't working but because you aren't printing the string value of your values. Try the following.
for(int i = 0; i < cases.length; i++){
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(Arrays.toString(cases[i]));
}

Writing a static method for the following code

I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());

how can I remove a room in arraylist Room by name?

I'm learning java. I have trouble about arraylist in my java program. How can I remove a room in arraylist in Room and count the number of rooms has the size smaller than 40. I just coded 2 methods which were removeRoom and countRoomBySize in class MyRoom. My code has error in Net Beans. Anyone help me to check this code, please. Thank so much. Here is my code
My Main class
public class MyMain {
public static void main(String[] args) {
//create a list of rooms
MyRoom m = new MyRoom();
m.addRoom(new Room("HB201L",35));
m.addRoom(new Room("HB401R",45));
m.addRoom(new Room("211",30));
m.sort();
m.list();
//1.
m.removeRoom("211");
m.list();
//2.
int c = m.countRoomBySize(40);
System.out.println(c);//2
}
}
Class Room
public class Room implements Comparable<Room> {
#Override
public int compareTo(Room o) {
return o.name.compareToIgnoreCase(this.name);
}
//instanced variables
private int size;
private String name;
public Room() {
name = "";
size = 0;
}
public Room(String name, int size) {
this.name = name;
this.size = size;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Class MyRoom
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MyRoom implements IRoom {
List<Room> rooms;
public MyRoom() {
rooms = new ArrayList();
}
#Override
public void addRoom(Room r) {
//append r to the end of list rooms
rooms.add(r);
}
#Override
public void list() {
for (int i = 0; i < rooms.size(); i++) {
Room r = rooms.get(i);
System.out.printf("%-20s%-10d\n",r.getName(),r.getSize());
}
}
#Override
public void removeRoom(){
for (int i = 0; i < rooms.size(); i++) {
if(rooms.get(i).getName() == "211")
rooms.remove(rooms);
}
}
#Override
public int countRoomBySize(){
int s,i,n;
n = rooms.size();
s = 0;
for(i=0;i<n;i++) {
if(rooms.get(i).getSize() > 40)
s++;
}
return(s);
}
public void sort() {
Collections.sort(rooms);
}
}
Interface IRoom
public interface IRoom {
//only contain public members: constants and method declaration
public final int MAX = 10;
public void addRoom(Room r);
public void list();
public void removeRoom();
public int countRoomBySize();
}
interface A {
void f();
}
interface B extends A {
void g();
}
interface C {}
First change your interface IRoom like this :
public void removeRoom(String name);
public int countRoomBySize(int size);
In the MyRoom class change removeRoom method like this :
#Override
public void removeRoom(String name){
for (int i = 0; i < rooms.size(); i++) {
if(name.equalsIgnoreCase(rooms.get(i).getName())){
rooms.removeIf(r -> r.getName().equals(name));
System.out.println("Removed !");
}
}
}
And the countRoomBySize method like this :
#Override
public int countRoomBySize( int size){
int s,i,n;
n = rooms.size();
s = 0;
for(i=0;i<n;i++) {
if(rooms.get(i).getSize() > size)
s++;
}
return(s);
}
Best of luck !
removeRoom can be shortened to: rooms.remove(rooms.indexOf("211")) or perhaps even rooms.remove("211");
Nice that you are starting to learn java.
The simplest solution here is to put your room in an Hashmap and store the room number as key;
public class MyMain {
public static void main(String[] args) {
Hashmap<String,Room> rooms = new Hashmap();
rooms.add("211",new Room("HB201L",35);
rooms.add("HB401R",new Room("HB401R",45);
rooms.remove("211");
int size = rooms.size();
int smallRooms = calculateSmallRooms(rooms.values(),30);
}
private int calculateSmallRooms(Collection<Room> rooms, int minimalSize) {
int smallRooms = 0;
for(Room room: rooms) {
if (room.size < minimalSize) {
smallRooms++;
}
return smallRooms;
}

Add objects with random variables using a loop

I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}

Categories