This is my first post on stack exchange so i'm not really sure what you need but here's my issue:
I am creating an inventory tracker for my java class and I am running into an issue where I can't use the method addItem(Item newItem) because the class Inventory isn't static and does not have a constructor. We have a UML Diagram
we are supposed to work off of and it doesn't include a constructor for Inventory and says nothing about static.
I'm not really sure what else you need but any help would be greatly appreciated!
Thanks!
public class InventoryTrackerInterface {
public Inventory inv;
public static void main(String[] args) {
//test item
Item b1 = new Item("abc",1,123,"01345");
}
}
public class Inventory {
private Item[] itemArray;
private int totalItems = 0;
public int getTotalNumberOfItems() {
return totalItems;
}
public Item getItem(int index) {
if (index < 0 || index >= totalItems) {
return null;
} else {
return itemArray[index];
}
}
public void addItem(Item newItem) {
if (newItem == null) {
System.out.println("Item not added.");
} else {
itemArray[totalItems] = newItem;
totalItems++;
}
}
public void saveInventoryToFile(String fileName) {
}
public void loadInventoryFromFile(String fileName) {
}
}
public class Item {
private String name;
private int quantity;
private double price;
private String upc;
private Item() {
}
public Item(String name, int qty, double price, String upc) {
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public String getUPC() {
return upc;
}
}
You do not need to explicitly define a constructor in order to instantiate a class. In such cases, a default constructor is automatically created.
UML diagrams will usually only indicate constructors in cases where you would need one with parameters, as in the case of Item.
You can either define your inv property as static:
public class InventoryTrackerInterface
{
public static Inventory inv;
public static void main(String args[])
{
// Test items
Item b2 = new Item("abc",1,123,"01345");
Item c2 = new Item("dfe",2,456,"56789");
// Inventory object
inv = new Inventory();
inv.addItem(b2);
inv.addItem(c2);
}
}
Or access it through an InventoryTrackerInterface instance:
public class InventoryTrackerInterface
{
public Inventory inv;
public static void main(String args[])
{
// Test items
Item b2 = new Item("abc",1,123,"01345");
Item c2 = new Item("dfe",2,456,"56789");
InventoryTrackerInterface instance = new InventoryTrackerInterface();
// Inventory object
instance.inv = new Inventory();
instance.inv.addItem(b2);
instance.inv.addItem(c2);
}
}
Related
I am trying to build an ArrayList that will contain objects. when i add an object to the list i want it to first check the array list for that object. and if it finds it i want it to increase a quantity variable in that object and not create a new object in the list. and then vice versa when removing objects. I have accomplished a way that works when removing an object. But i dont think i fully understand the methods in the arraylist or the logic when creating and arraylist of objects. as when i use .contains or .equals im not getting the desired effect.
public class ItemBag {
private ArrayList<Item> inventory = new ArrayList<Item>();
public ItemBag() {
}
public void addItem(Item objName, int quantity) {
if (inventory.contains(objName)) {
System.out.println("if statement is true!");
int i = inventory.indexOf(objName);
inventory.get(i).setQuantity(inventory.get(i).getQuantity() + quantity);
} else {
inventory.add(objName);
objName.setQuantity(quantity);
}
}
public void removeItems(String itemName, int quantiy) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).name() == itemName) {
inventory.get(i).setQuantity(inventory.get(i).getQuantity() - quantiy);
if (inventory.get(i).getQuantity() <= 0) {
inventory.remove(inventory.get(i));
}
}
}
}
public void showInventory() {
for (int i = 0; i < inventory.size(); i++) {
System.out.println(inventory.get(i).name() + " : " + inventory.get(i).getQuantity());
}
}
then when creating the itemBag in another object i am writing
ItemBag merchantItems = new ItemBag();
public void merchantBob() {
merchantItems.addItem(new HealthPotion() ,3);
merchantItems.showInventory();
System.out.println("add 1");
merchantItems.addItem(new HealthPotion(),1);
merchantItems.showInventory();
Items class
package Items;
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
HealthPotion Class
public class HealthPotion extends Potions {
protected int addHealth = 10;
#Override
public int drinkPotion() {
return addHealth;
}
#Override
public String name() {
return "Health Potion";
}
#Override
public int cost() {
return 5;
}
#Override
public String type() {
return "Potion";
}
}
The .contains() method would iterate through the list and use .equals() method to compare each element and check if the provided object exists in the list.
.equals() method would compare the object reference (unless .equals() is overridden) to check if the objects are same.
For reference: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#contains-java.lang.Object-
You can override the .equals() method to compare the values of the provided object in the following way:
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Item providedItem = (Item) object;
return name == providedItem.name
&& cost == providedItem.cost
&& type == providedItem.type;
}
}
This should work
I want to create a method which returns a Boolean value. It should return true if the sale is over 5 years old or older and false if the sale is under 5 years.
I have given it an attempt but I cannot seem to get it work. If anyone can think over a more efficient way of completing this I am open to a different direction.
I have tried the below but the method continue to error out no matter what I change. Google has not been helpful either as the method is so specific.
the method is called isSaleOld() (Go to the bottom of the code)
Thank you for any help in advance. Code is below for the whole project.
public class Sale
{
// instance variables
private String company;
private String yearBought;
private int saleValue;
private Seller seller;
public Sale(String aCompany, String aYear, int aValue,
Seller theSeller)
{
this.company = aCompany;
this.yearBought = aYear;
this.saleValue = aValue;
this.seller = theSeller;
}
public void setSellersName(String aName)
{
this.seller.setName(aName);
}
public void setSaleValue(int aValue)
{
this.saleValue = aValue;
}
public void setyearBought(String aYear)
{
this.yearBought = aYear;
}
public void setCompany(String aCompany)
{
this.company = aCompany;
}
public int getSaleValue()
{
return this.saleValue;
}
public boolean isApprovalRequired()
{
return this.getSaleValue() >=10000;
}
public String getYearBought()
{
return this.yearBought;
}
public void isSaleOld(String[] args)
{
yearBought = getYearBought("2020");
boolean after = yearBought.after(yearBought);
}
}
import java.time.LocalDateTime;
public class Sale {
private int yearBought;
public void sale(int year) {
setYearBought(year);
}
private int getYearBought() {
return this.yearBought;
}
private void setYearBought(int year) {
this.yearBought = year;
}
public boolean isSaleOld() {
int now = LocalDateTime.now().getYear();
int yearBought = getYearBought();
if (now - yearBought > 5) {
System.out.println("Yes, older than 5 years");
return true;
}
System.out.println("No, less than 5 years old");
return false;
}
public static void main(String[] args) {
Sale sale = new Sale();
Sale sale2 = new Sale();
sale.sale(2010);
sale2.sale(2020);
sale.isSaleOld();
sale2.isSaleOld();
}
I have an issue with JavaFX TableView UI update. After I change the observable object, it does not update the UI of TableView. But if I perform a magical ritual of pulling TableView's scroll bar down and up again - it seems to redraw the table and update items in it.
Through debugging I've ensured, that the PreferencesSet ArrayList and object are updated correctly.
Here's gif demonstration of what is happening
This is my first time asking a question here, so I could have left out some important info. Feel free to ask me for it. Thank you in advance.
Here's code (I have left out unrelated stuff):
ControllerClass:
public class TestSomethingController implements Initializable {
public TableView<PreferenceValues.PreferencesSet> preferencesTable;
public TableColumn mdColumn;
public TableColumn typeColumn;
public TableColumn tradeColumn;
public TableColumn plastColumn;
public TableColumn capColumn;
public TableColumn multColumn;
public TableColumn sizeColumn;
#Override
public void initialize(URL location, ResourceBundle resources) {
setNorthPanel();
setTableColumns();
fillAllInfo();
}
private void setTableColumns() {
mdColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, MarketDirection>("md"));
typeColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, UserOfferType>("type"));
tradeColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, Boolean>("trade"));
plastColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, Long>("plast"));
capColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, Double>("cap"));
multColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, Double>("mult"));
sizeColumn.setCellValueFactory(new PropertyValueFactory<PreferenceValues.PreferencesSet, Long>("size"));
}
private void fillAllInfo() {
preferencesTable.setItems(FXCollections.observableArrayList(CurrentSession.currentUser.getPreferencesList()));
fillNorthPanel();
}
public void applyClicked(ActionEvent actionEvent) {
applyNorthPanelChanges();
}
private void applyNorthPanelChanges() {
PreferenceValues.PreferencesSet preferencesSet = CurrentSession.currentUser.getPreferencesSet(dirChoiceBox.getSelectionModel().getSelectedItem(), offerTypeChoiceBox.getSelectionModel().getSelectedItem());
preferencesSet.setTrade(tradeCheckBox.isSelected());
preferencesSet.setPlast(plastSpinner.getValue());
preferencesSet.setCap(capRateSpinner.getValue());
preferencesSet.setMult(multSpinner.getValue());
preferencesSet.setSize(sizeSpinner.getValue());
preferencesSet.savePreferences();
}
User class:
public class User {
private PreferenceValues preferenceValues;
public PreferenceValues.PreferencesSet getPreferencesSet(MarketDirection md, UserOfferType userOfferType) {
return preferenceValues.getPreferencesSet(md, userOfferType);
}
public ArrayList<PreferenceValues.PreferencesSet> getPreferencesList() {
return preferenceValues.getPreferencesList();
}
}
PreferenceValues class:
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class PreferenceValues {
private Preferences preferences;
private ArrayList<PreferencesSet> preferencesList;
private TreeMap<String, PreferencesSet> preferencesMap;
public PreferenceValues(User user) {
preferencesList = new ArrayList<>();
preferencesMap = new TreeMap<>();
preferences = Preferences.userRoot().node("prefexample" + user.getwmId());
for (MarketDirection md : MarketDirection.values()) {
for (UserOfferType userOfferType : UserOfferType.values()) {
if (userOfferType != UserOfferType.UNDEF) {
PreferencesSet preferencesSet = new PreferencesSet(md, userOfferType, preferences);
preferencesList.add(preferencesSet);
preferencesMap.put(md.toString() + userOfferType.toString(), preferencesSet);
}
}
}
}
protected ArrayList<PreferencesSet> getPreferencesList() {
return preferencesList;
}
private String getMapKey(MarketDirection md, UserOfferType userOfferType) {
return md.toString() + userOfferType.toString();
}
protected PreferencesSet getPreferencesSet(MarketDirection md, UserOfferType userOfferType) {
return preferencesMap.get(getMapKey(md, userOfferType));
}
public void clear() throws BackingStoreException {
preferences.clear();
}
public class PreferencesSet {
Preferences preferences;
private MarketDirection md;
private UserOfferType type;
private boolean trade;
private int plast;
private double cap;
private double mult;
private int size;
public PreferencesSet(MarketDirection md, UserOfferType type, Preferences preferences) {
this.md = md;
this.type = type;
this.preferences = preferences;
trade = preferences.node(md.toString()).node(type.toString()).getBoolean("trade", false);
plast = preferences.node(md.toString()).node(type.toString()).getInt("plast", 222);
cap = preferences.node(md.toString()).node(type.toString()).getDouble("cap", 333);
mult = preferences.node(md.toString()).node(type.toString()).getDouble("mult", 1);
size = preferences.node(md.toString()).node(type.toString()).getInt("size", 15000);
}
public void savePreferences() {
preferences.node(md.toString()).node(type.toString()).putBoolean("trade", trade);
preferences.node(md.toString()).node(type.toString()).putInt("plast", plast);
preferences.node(md.toString()).node(type.toString()).putDouble("cap", cap);
preferences.node(md.toString()).node(type.toString()).putDouble("mult", mult);
preferences.node(md.toString()).node(type.toString()).putInt("size", size);
}
public MarketDirection getMd() {
return md;
}
public UserOfferType getType() {
return type;
}
public boolean isTrade() {
return trade;
}
public int getPlast() {
return plast;
}
public double getCap() {
return cap;
}
public double getMult() {
return mult;
}
public int getSize() {
return size;
}
public void setTrade(boolean trade) {
this.trade = trade;
}
public void setPlast(int plast) {
this.plast = plast;
}
public void setCap(double cap) {
this.cap = cap;
}
public void setMult(double mult) {
this.mult = mult;
}
public void setSize(int size) {
this.size = size;
}
}
}
Since the only way for PropertyValueFactory to retrieve the value is using the getter, changes of a property cannot be observed and therefore the update only happens, when the item is associated with a new TableRow.
Starting with JavaFX 8u60 you can simply call the refresh method of TableView, which will force an update to be executed.
However the usual way of doing this is by providing access to a property object containing the property value, e.g.
In PreferencesSet
private final IntegerProperty plast = new SimpleIntegerProperty();
public void setPlast(int plast) {
this.plast.set(plast);
}
public int getPlast() {
return plast.get();
}
// this method will be used by the PropertyValueFactory
// and returns a Property which notifies TableView of changes
public IntegerProperty plastProperty() {
return plast;
}
There are other property types for the other data types, see javafx.beans.property package
I have got an array of 20:
private Karte[] deckArr;
deckArr = new Karte[20];
Now I want to sort the array by card-names every time a new card is added.
P.S. the cards are added 1 by 1 after clicking on a button, so there are empty spaces in the array.
Since the...
Arrays.sort(deckArr.getName());
...method does not work here I asked myself how it is done.
Karte(card) class:
package Model;
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements ComparableContent<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
#Override
public boolean isLess(Karte karte) {
if (getName().compareTo(karte.getName()) < 0){
return true;
}else{
return false;
}
}
#Override
public boolean isEqual(Karte karte) {
return getName() == karte.getName();
}
#Override
public boolean isGreater(Karte karte) {
if (getName().compareTo(karte.getName()) > 0){
return true;
}else{
return false;
}
}
}
Any help is appreciated!
Why not just use ArrayList instead? Easier to add, remove elements and you will never have empty slots.
Anyway to sort you can use Collections.sort like this:
deckArr = new ArrayList<Karte>();
Collections.sort(deckArr, Comparator.comparing(karte -> karte.getName()));
Java 8 offers a simple solution:
The Comparable Interface has a static method that creates a Comaprator with an extractor.
Comparator<Card> comp = Comparator.comparing(Karte::getName);
With this using a sorting method (e.g. Arrays.sort) is easy to call.
On top of that, to solve your nullpointer problem, the Comparator Interface offers another two functions: NullsLast and nullsFirst.
Comparator<Card> comp = Comparator.nullsLast(Comparator.comparing(Card::getName));
For me this looks like the easiest solution to your question :)
This should solve your problem. Implements the Comparable interface.
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements Comparable<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
public int compareTo(Karte karte) {
return this.name.compareTo(karte.getName());
}
}
Then you just need to call Arrays.sort(deckArr);
You need to check for nulls and just call below--
Arrays.sort(deckArr, new Comparator<Karte>() {
#Override
public int compare(Karte karte1, Karte karte2) {
if (karte1.getName() == null && karte2.getName() == null) {
return 0;
}
if (karte1.getName() == null) {
return 1;
}
if (karte2.getName() == null) {
return -1;
}
return karte1.getName().compareTo(karte2.getName());
}});
I am trying to add objects to my ArrayList friends... I get this error,
The method add(int, Person) in the type ArrayList is not
applicable for the arguments (int, String)
I am trying to add a few instances of my person object to eventually create a tree of friends.
import java.util.*;
public class Person
{
public int id; // some identification number unique to the person
public boolean zombie; // true if the person is a zombie
public char state; // p means human, z means zombie
public static ArrayList<Person> friends; // list of friends
public Person(int id, char state)
{
this.id = id;
this.state = state;
//this.zombie = zombie;
}
public static void addPeople()
{
friends = new ArrayList<Person>();
friends.add(1, 'p');
}
public boolean isZombie()
{
if (state == 'p')
{
return zombie=false;
}
else if (state == 'z')
{
return zombie=true;
}
return zombie;
}
}
The error is located under the "add" word. I would also like to know how I can name the instances of the object so I only call the name rather than the two attributes.
Thanks in advance for all help.
import java.util.ArrayList;
import java.util.List;
/**
* Person description here
* #author Michael
* #link http://stackoverflow.com/questions/15799429/why-am-i-getting-this-error-when-adding-object-to-arraylist-java/15799474?noredirect=1#comment22468741_15799474
* #since 4/3/13 9:45 PM
*/
public class Person {
private Integer id;
private boolean zombie;
private List<Person> friends;
public static void main(String [] args) {
List<Person> lastPeopleStanding = new ArrayList<Person>();
for (int i = 0; i < 3; ++i) {
lastPeopleStanding.add(new Person(i));
}
lastPeopleStanding.get(0).addFriend(lastPeopleStanding.get(1));
lastPeopleStanding.get(0).addFriend(lastPeopleStanding.get(2));
System.out.println(lastPeopleStanding);
}
public Person(Integer id) {
this.id = id;
this.zombie = false;
this.friends = new ArrayList<Person>();
}
public boolean isZombie() { return this.zombie; }
// Irreversible! Once you go zombie, you don't go back
public void turnToZombie() { this.zombie = true; }
// Only add a friend if they're not a zombie
public void addFriend(Person p) {
if (p != null && !p.isZombie()) {
this.friends.add(p);
}
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Person{");
sb.append("id=").append(id);
sb.append(", zombie=").append(zombie);
sb.append(", friends=").append(friends);
sb.append('}');
return sb.toString();
}
}
You forgot to create a new Person to add to your ArrayList:
From your comment, you can create a class member variable called idCount and increment when a Person is added:
public void addPeople() {
friends.add(new Person(++idCount, 'p'));
}
Using static methods is generally considered poor design for a class that can have state.