searching objects in a class - java

I'm making a program, in school, that plays monopoly and I set up all the own-able properties as objects in the property class and I want to be able to search for the properties by their position value. so if the player's position is 3 (which is Baltic Ave. in my code) I want to be able to search all own-able properties for one with a position of 3 then have the player buy/pay rent for the property. Is this possible or should I go at the problem from a different angle?
public class property
{
String owner;
int position;
int price;
int rent;
public property(int startPrice, int startPosition, int startRent)
{
price = startPrice;
position = startPosition;
owner = "none";
rent = startRent;
}
public void setOwn(String newOwn)
{
owner = newOwn;
}
public void changePrice(int newprice)
{
price = newprice;
}
public void changeRent(int newRent)
{
rent = newRent;
}
public int getprice()
{
return price;
}
public int getpos()
{
return position;
}
public String getown()
{
return owner;
}
public int getrent()
{
return rent;
}
}

To start, I'd have some sort of data structure to keep track of properties that can be bought. A HashSet is best since order doesn't matter and you can add and remove elements quickly. Set it up so that it contains properties that can be bought. Then I'd make this method: (don't put it in your Property class)
private static Property getPropertyAtPos(Player player, HashSet buyableProperties) {
for(Property p : buyableProperties) {
if(p.position == player.position) {
return p;
}
}
return null;
}
Call this method to get the property that can be bought by that player. Hope this helps.

Related

Why do I keep getting a Null Exception Error?

I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin can hold upto a maximum of 3 passengers. I'm trying to set passenger details but i keep getting this error
Cannot invoke "classes.Passenger.setFirstName(String)" because
"classes.Main.myShip[0].passenger[0]" is null at
classes.Main.main(Main.java:22)
Ship.java
public class Ship
{
public static Scanner scanner = new Scanner(System.in);
public static Cabin[] myShip = new Cabin[12];
public static void main(String[] args)
{
for (int count = 0; count < 12; count++)
{
myShip[count] = new Cabin();
}
myShip[0].passenger[0].setFirstName("a");
}
}
Cabin.java
public class Cabin
{
int cabinNumber;
Passenger[] passenger = new Passenger[3];
public Cabin()
{
}
public Cabin(int cabinNumber, Passenger[] passenger)
{
this.cabinNumber = cabinNumber;
this.passenger = passenger;
}
public void setCabinNumber(int cNumber)
{
cabinNumber = cNumber;
}
public int getCabinNumber()
{
return cabinNumber;
}
}
Passenger.java
public class Passenger
{
String firstName;
String lastName;
int expenses;
public Passenger()
{
}
//Constructors
public Passenger(String cabinFirstName, String cabinLastName, int pExpenses)
{
firstName = cabinFirstName;
lastName = cabinLastName;
expenses = pExpenses;
}
public void setFirstName(String cabinFirstName)
{
firstName = cabinFirstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String cabinLastName)
{
lastName = cabinLastName;
}
public String getLastName()
{
return lastName;
}
public void setExpenses(int pExpenses)
{
expenses = pExpenses;
}
public int getExpenses()
{
return expenses;
}
}
Please be kind enough to help me out.
Your model is wrong. A ship can (and does) have cabins with no occupants. You have provided no way to have unoccupied cabins. Your cabins need to be fully booked before the ship can be built!
I would consider redefining your Cabin class to be constructed empty -- which means it would have a constructor with a signature like Cabin(), and then provide a way to assign Passengers to Cabins. Maybe this would be a method in the Cabin class, like
boolean assignPassenger(Passenger p) {
... check occupancy...
... return false if full up ...
... otherwise add 'p' to the passenger array ...
... and return true ...
}
You're halfway there in that you're attempting to set the Cabins in the Ship by using a Cabin() constructor -- which is essentially an empty Cabin -- but you have not actually implemented a constructor with that signature.
What I'm getting at here is that, rather than just tweaking some Java, I think you should rethink it a bit. You'd want, I think, to be able to have unoccupied cabins and to be able to determine which cabins are occupied.

Java Game - Pick up Item and Look around Function

I have been creating a java text game but I am stuck trying to figure out on how to implement the last 2 methods. I want it to print out the items in the room and the name of the npc thats in the room (A sort of a Look function). I am not sure on how to go on about it. Any help would be appriciated.
Room[] place = new Room[]{station, UC, Ollies, lounge, palace, AT301};
Sword sword = new Sword();
Thing heal = new HealthPotion();
Thing armour = new Armour();
Thing trap = new Trap();
and for the NPC (Mike, Jake, Evil, Carl)
public abstract class Player{
//abstract attributes
private String name;
private int currentHealth;
private int maxHealth;
private int damage;
private Room currentRoom;
private int stack;
private int effect;
//Constructor for player
public Player(String name, int currentHealth, int maxHealth, int damage, int effect, int stack){
this.name = name;
this.currentHealth = currentHealth;
this.maxHealth = maxHealth;
this.damage = damage;
this.effect = effect;
this.stack = stack;
}
//getters
public String getName(){ return name;}
public int getCurrentHealth(){ return currentHealth;}
public int getMaxHealth(){ return maxHealth;}
public int getDamage(){ return damage;}
public Room getCurrentRoom(){ return currentRoom;}
public int getEffect(){ return effect;}
public int getStack(){ return stack;}
//setters
public void setCurrentHealth(int currentHealth){this.currentHealth = currentHealth;}
public void setMaxHealth(int maxHealth){this.maxHealth = maxHealth;}
public void setDamage(int damage){ this.damage = damage;}
public void setCurrentRoom(Room room){this.currentRoom = room;}
public void setEffect(int effect){ this.effect = effect;}
public void setStack(int stack){ this.stack = stack;}
public void enter(Room room){ this.currentRoom = room;}
//abstract method because each player has a different attack;
public void takeDamage(int damage){ setCurrentHealth(this.currentHealth-damage);}
public boolean isDead(){
if(this.currentHealth<=0){ return true;}
return false;
}
}
I was able to make everything functional except the Look function for the player. I can't figure out how to go on about it.
Room is a vector of items right ? If so you can do a function on the player class that when it is called it goes to the vector of the room you're in and simply print out the items that are in the vector, something like this:
String lookAround(){
ArrayList temp = (ArrayList)getCurrentRoom(); //returns the array containing the items in the current room
for(Thing i : temp){
i.getDescription(); //Method present in all classes that come from Thing that prints out the name of the item and/or its caracheteristics
}
}
In the array of the room you should try to include the name of all players in the room including yourself so that you can print out everyone present in the room
Hope this helps
I would recommend you first of all creating a class Npc with attribute name and add it to the room.

JOptionPane not displaying all items from ArrayList

I am trying to write a program that will create a food order consisting of food items displayed from a menu. Each item is selected and given a certain quantity. I want to display the items that I select in a JTextField but it has not been working correctly.
There are a few problems that I have ran into and cannot seem to figure out,
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
The following is my are all of my class files.
import java.util.ArrayList;
public class Menu {
private final ArrayList<Item> menu;
public Menu() {
menu = new ArrayList<>();
}
public void addItem(Item item) {
menu.add(item);
}
public Item getItem(int itemNo) {
if (menu.size() > itemNo) {
return menu.get(itemNo);
}
return null;
}
#Override
public String toString() {
for (int i = 0; i < menu.size(); i++) {
return String.format("%s: %s \n",i+1, menu.get(i));
}
return null;
}
}
public class Item {
private final String name;
private final double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return String.format("Name %s # Price $%s", name, price);
}
public boolean equals(Item item) {
return item.name.equals(item.name);
}
}
public class ItemQty {
private final Item item;
private final int quantity;
public ItemQty(Item item, int quantity) {
this.item = item;
this.quantity = quantity;
}
public Item getItem() {
return item;
}
public int getQuantity() {
return quantity;
}
#Override
public String toString() {
return String.format("%s - %s\n", quantity, item);
}
public boolean equals(ItemQty itemQty) {
return itemQty.getItem().equals(itemQty.getItem());
}
}
import java.util.ArrayList;
public class Order {
private final ArrayList<ItemQty> order;
public Order() {
order = new ArrayList<>();
}
public void addToOrder(ItemQty itemQty) {
if (order.contains(itemQty)) {
int amount = itemQty.getQuantity();
amount += 1;
}
else
order.add(itemQty);
}
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
#Override
public String toString() {
String str = "";
for (int index = 0; index < order.size(); index++) {
str += order.get(index).toString() + "\n\n";
}
return str;
}
}
Any help or critiques would be appreciated
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
This is due to the fact that you're returning the value of sum only after the first iteration of your loop
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
Something like...
public double getTotalPrice() {
double sum = 0;
for (Order item : order) {
double price = item.getItem().getPrice();
int quantity = item.getQuantity();
sum += (price * quantity);
}
return sum;
}
would work better
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
Since there is no JOptionPane in your code, it's impossible to know what the issue might be
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
Okay, this is a lot more difficult, because you code doesn't really provide enough support to do it.
There's no way for your code to update the quantity information after the ItemQty is created, you will need to supply a setter of some kind to perform this action (or a add method, to which you pass another ItemQty and it does the job for you)
First, I'd add a new method to ItemQty
public class ItemQty {
//...
public void add(int quantity) {
this.quantity += quantity;
}
}
This just makes it possible to increase the quantity.
Second, I'd change the Order#addToOrder, I'd make it so you had to pass an Item and a quantity to it (other classes don't need to make a ItemQty object in this case). In this method, I'd search for a matching item and either update it or add it to the order.
public class Order {
//...
public void addToOrder(Item item, int quantity) {
List<ItemQty> matches = order.stream().filter((itemQty) -> {
return itemQty.getItem().equals(item);
}).collect(Collectors.toList());
if (matches.size() > 0) {
matches.get(0).add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}
Okay, that might have you scratching your head, it does me, but basically, it's just a fancy pancy way for saying...
public void addToOrder(Item item, int quantity) {
ItemQty match = null;
for (ItemQty check : order) {
if (check.getItem().equals(item)) {
match = check;
break;
}
}
if (match != null) {
match.add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}

Java - Scanning Items in an ArrayList

I have a class which creates a 'Purchase' object. This object can be recorded to an ArrayList 'purchaseList' using the recordItem() method. However, I want to create a function that can return a specific Purchase object given an itemNo integer, I have shown my code so far in getPurchase() but am having trouble getting it working.
public class Purchase {
private String name;
private double price;
private int itemNo;
private int sort;
private ArrayList purchaseList = new ArrayList();
public Purchase(String name, double price, int itemNo, int sort) {
this.name = name;
this.price = price;
this.itemNo = itemNo;
this.sort = sort;
}
public void recordItem(int itemNumber, String description, double unitPrice, int sort) {
Purchase newPurchase = new Purchase(description, unitPrice, itemNumber, sort);
purchaseList.add(newPurchase);
}
public int getItemNo() {
return itemNo;
}
public Purchase getPurchase(int itemNumber) {
for(int i = 0; i < purchaseList.size(); i++) {
if(purchaseList[i].getItemNo() == itemNumber) {
return purchaseList[i];
}
else return 0;
}
}
}
purchaseList[i] is valid when you work with arrays.
When working with List objects, to retrieve the ith element, you have to invoke the List.get(int index) method. Like this:
purchaseList.get(i)
And so, your method has to be refactored to:
public Purchase getPurchase(int itemNumber) {
for(int i = 0; i < purchaseList.size(); i++) {
if(purchaseList.get(i).getItemNo() == itemNumber) {
return purchaseList.get(i);
}
else return 0;
}
}
Also, in order to avoid casting from Object to Purchase, you have to make your List generic.
private List<Purchase> purchaseList = new ArrayList<Purchase>();
This way the compiler will ensure that the objects you add to the list are of type Purchase and will not force you to cast them to something specific when being got.
Change your purchaseList[i].getItemNo() to purchaseList.get(i).getItemNo()
Your getPurchase() method logic is incorrect. You shouldn't exit after the first condition is not met.
Try changing it like this:
// Change the declaration like this
private List<Purchase> purchaseList = new ArrayList<Purchase>();
// And change the method like this:
public Purchase getPurchase(int itemNumber) {
for(Purchase purchase : purchaseList) {
if(purchase.getItemNo() == itemNumber) {
return purchase;
}
}
return null;
}
Also recordItem() and getPurchase() don't look like they belong inside the Purchase class.

monopoly property multiple owner

I'm creating a Monopoly program in Java and I run into a problem: When a player lands on a Property always get's to buy it, even if it's already owned.
Here are the two pieces of code that come in question:
Property class:
class Property{
public int ownerID = -1;
public Player owner;
public boolean isOwned;
public int price, rent; // defined in Constructor
public void onLanded(Player p){
if(OwnerID < 0){
p.offerProperty(this);
} else if(ownerID != p.getID(){
p.transfer(-rent);
owner.transfer(rent);
System.ou.println("bla bla");
} else {
System.out.println("bla bla");
}
}
public void buy(Player p){
p.transfer(-price);
setOwner(p);
p.assets.add(this);
}
public void setOwner(Player p){
owner = p;
ownerID = p.getID();
isOwner = true;
}
}
class Player:
class Player{
int id, money; // defined in Constructor
ArrayList<Property> assets = new ArrayList<Property>();
public void offerProperty(Property p){
if(money >= p.getPrice()){
System.out.println("wanna bu?");
String inputAnswer = scanner.next();
if(agreed(inpuAnswer))
p.buy(this);
}
}
public boolean agreed(String s){
if(s.equals("yes") return true;
return false;
}
public int getID(){
return id;
}
public void transfer(int amount){
money += amount;
}
}
Now, as I said, every time I run the game I get that if a player lands on a already owned property, he get the possibility to buy it instead of having to pay the rent to the owner. I have been looking for solutions for days and I also tried some other approach to the problem but always unsuccessful. Does anybody have an idea how to solve this issue?
In class Property, change this method:
public void buy(Player p) {
if (owner == null) {
p.transfer(-price);
setOwner(p);
p.assets.add(this);
}
}
I found my bug, and it wasn't actually in the piece of code I wrote in the question. :)
The bug was that every time a player moves, he creates a new board and moves on it, so the property is always not owned.

Categories

Resources