Access existing objects in another class Java - java

I'm using Bluej to create a basic Java project which I'm not supposed to use Arrays or collections and I'm having difficulty to understand how I can display a specific existing object from another class.
Here's my Class Listing:
public class Listing
{
//name of the listing
private String listingName;
//number of the listing
private int listingNumb = 0;
//price of the listing
private double price;
//checks if the listing is for sale
private boolean isForSale;
//House data of the listing
private HouseData housedata;
private boolean isSold;
/**
* Constructor for objects of class Listing
*/
public Listing(String newListing, double newPrice, HouseData housedata)
{
listingName = newListing;
listingNumb++;
price = newPrice;
isForSale = false;
this.housedata = housedata;
isSold = false;
}
//Returns if the listing is sold or not
public boolean getIsSold(){
return isSold;
}
//Set the listing as sold or not
public boolean setIsSold(){
isSold = true;
return isSold;
}
//returns if the listing is for sale or not
public boolean getIsForSale(){
return isForSale;
}
//set the listing for sale or not
public boolean setIsForSale(boolean sale){
isForSale = sale;
return isForSale;
}
//Return the price of the listing
public double getPrice(){
return price;
}
//Return the listing name
public String getListingName(){
return listingName;
}
//Return the listing number
public int getListingNumb(){
return listingNumb;
}
//checks if the listing is located at a specific city
public boolean isLocatedAt(String city){
if(housedata.city() == city){
return true;
}else{
return false;}}
public double getSurface(){
return housedata.getSurface();
}
}
Here's my Class RealEstateAgency where I want to call the objects from class Listing:
public class RealEstateAgency
{
//the name of the agency
private String agency;
//the amount of profit from property sales
private double profit;
//identifies the seller of the property
private String agent;
private boolean isOnSale;
//the name of the property
private Listing listing;
private Listings lists;
/**
* Constructor for objects of class RealEstateAgency
*/
public RealEstateAgency()
{
profit = 0;
}
//Returns total profit from agency
public double getProfit(){
return profit;
}
//Display listing that is on sale with the name of one city
//This is the method where I want to retrieve all listing existing objects that have a specific city
public void displayListingsLocatedAt(String city){
System.out.println("The available listings for this city are: " + ;
}
}
And this is the main class where I initialize the objects:
public class AppStart
{
public static void main(String[] args)
{
Address address1 = new Address("street", "postalcode", "city");
HouseData house1 = new HouseData(2, true, address1);
Listing list1 = new Listing("Imóvel1", 9000, house1);
Listing list2 = new Listing("Imóvel2", 9000, house1);
Listing list3 = new Listing("Imóvel3", 8000, house1);
RealEstateAgency real1 = new RealEstateAgency();
}
}

Thing is, you are creating these Listing classes that are not part of any class. After your initialization of RealEstateAgency, there should be a call something like this:
real1.listing = list1;
(I think it will work, altough it's set to private...)
It will add your list1 into your real1 object, then able to call it's getters like
real1.listing.getPrice();
Or something like this.
Thing is, you can reach the class variables by the dot selector, even if that variable is an another class, in that case you can use your selectors as a chain.
However, with your current setup, you can hold only 1 Listing in each RealEstateAgency, plus I don't think "Listings lists" works. Either that's an errorenous code, or part of your code is missing that explains that line.
An another note, your listingNumb currently does nothing, since it's held by the Listing class, so after calling the constructor of a Listing, it will be just set to 1 all the time.

Related

Add array from list into a new set in Java

I want to get the model numbers from the list only
['brand: Samsung, model number: VA2210-MH, size: 21.5', 'brand: Philipe, model number: 244E1SB, size: 21.5']
And I set create attributes and getter and setter of all attributes(only model number will be shown) in Monitor
public class Monitor{
public String brand;
public String modelNumber;
public double size;
public Monitor(String brand, String modelNumber, double size){
this.brand = brand;
this.modelNumber = modelNumber;
this.size = size;
}
public void setModelNumber(String amodelNumber){
modelNumber = amodelNumber;
}
public String getModelNumber(){
return modelNumber;
}
}
so I create a list and add the information into the list
and a method to create a set with model number by the method modelNumberSet()
import java.util.*;
public class ComputerShop{
private List<Monitor> monitorList = new ArrayList<>();
public void addMonitor(String brand, String modelNumber, double size){
Monitor newMonitor = new Monitor(brand, modelNumber, size);
monitorList.add(newMonitor);
}
public Set<Monitor> modelNumberSet(){
Set<Monitor> NewSet = new HashSet<>();
for (Monitor m : monitorList) {
NewSet.add(m.getModelNumber());
}
return NewSet;
}
}
I hope the model number will be added into a new set, the output looks like
[VA2210-MH, 244E1SB]
So I use for loop to incase I will add more information in the future, but the error comes out when I use add(). Why the array cannot be added into the new set? Am I using the wrong function?
Is there a better solution I should use?
Change Set<Monitor> to Set<String>. You are adding model numbers to the set and their types are String. You are trying to put a String where a Monitor is expected. Square peg in a round hole.
Fix the modelNumberSet() method as follows:
public Set<String> modelNumberSet(){
Set<String> newSet = new HashSet<>();
for (Monitor m : monitorList) {
newSet.add(m.getModelNumber());
}
return newSet;
}

Only Allow Objects with Unique Name - Java

I am making an inventory system.
I want to ensure that objects I am creating (Ingredients) all have unique names. In other words, I want to make sure that there are never two Ingredients that have the same name in the whole program. Currently I have the following class:
package ingredient;
import java.util.HashSet;
public class Ingredient {
private final String name;
private final double price;
private static HashSet<String> names = new HashSet<String> ();
private Ingredient(String ingr_name, double ingr_price) {
name = ingr_name;
price = ingr_price;
}
public static Ingredient createIngredient(String ingr_name, double ingr_price) {
if (names.contains(ingr_name)) {
return null;
} else {
names.add(ingr_name);
return new Ingredient(ingr_name, ingr_price);
}
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
Then, when I go to actually make new ingredients, I make statements such as :
Ingredient egg = Ingredient.createIngredient("egg", 1);
Is this okay design? I suppose I am concerned because returning "NULL" might not be the best practice here.
I cant comment, but whatever...
I would go about this by storing all of the Ingredients in a different class, then you wouldn't need all this static nonsense. In the class where you actually create a new Ingredient (Ingredient egg = Ingredient.createIngredient("egg", 1);) you could maybe create an ArrayList of ingredients like so:
ArrayList<Ingredient> ingredients = new ArrayList<>();
Then when you make a new Ingredient you would just have to make sure you add it to the ArrayListand when you do so, check that none of the ingredients are already there, maybe something like this:
createIngredient("egg", 1);
or
Ingredient egg = createIngredient("egg", 1);
...
private Ingredient createIngredient(String ingr_name, double ingr_price){
for(Ingredient i : ingredients){
if(i.getName().equals(ingr_name)){
return null;
}
}
Ingredient newing = new Ingredient(ingr_name, ingr_price);
ingredients.add(newing);
return newing;
}
Then the Ingredient class could be cut down to something like this:
package ingredient;
public class Ingredient {
private final String name;
private final double price;
public Ingredient(String ingr_name, double ingr_price) {
name = ingr_name;
price = ingr_price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
And then you could access each individual Ingredientwith a method to run through the ArrayList and find the Ingredient with the name your looking for:
public Ingredient findIngredient(String name){
for(Ingredient i : ingredients){
if(i.getName().equals(name)){
return i;
}
}
return null;
}
I would recommend either
A) returning the already created ingredient
Or if that would confuse the caller,
B) throwing an exception
This can be a simple IllegalArgumentsException, or depending on your needs, a custom exception class.

Infinite loop when trying to populate a list of no more than two Hospitals

In this project the user must enter 1 or 2 hospitals but not 3 or more. So the program starts and I display a menu. If the user presses 1 he must enter a hospital(name and department). After this the program displays the menu again and the user can choose to insert another hospital.
But after that, if I choose to insert another one (which is not permitted) the program accepts it. It seems that every time InsertHospitals() is called from the main class, the value of numberofhospitals (which is a counter counting how many hospitals I entered) equals 0.
public class Hospital {
private String Name, Departments;
private char flag;
private int numberofhospitals;
private Hospital[] ListOfHospitals;
//private Patient[] ListOfPatiens;
//private Doctor[] ListOfDoctors;
//private Examination[] ListOfExaminations;
//private Folder[] ListOfFolders;
public Hospital(String Name, String Departments)
{
this.Name=Name;
this.Departments=Departments;
}
public Hospital()
{
ListOfHospitals = new Hospital[2];
//ListOfPatiens = new Patient[100];
//ListOfDoctors = new Doctor[100];
//ListOfExaminations = new Examination[100];
//ListOfFolders = new Folder[100];
}
public String getName()
{
return Name;
}
public void setname(String Name)
{
this.Name=Name;
}
public String getDepartments()
{
return Departments;
}
public void setdepartments(String Departments)
{
this.Departments=Departments;
}
public void InsertHospitals()
{
if(numberofhospitals==2)
{
System.out.println("You can give only two hospitals!");
}
else
{
String temp = sir.readString("Hospital's Name:");
Name=temp;
String temp1 = sir.readString("Hospital's departments:");
Departments=temp1;
Hospital hospital = new Hospital(Name, Departments);
ListOfHospitals[numberofhospitals]=hospital;
numberofhospitals=numberofhospitals+1;
}
}
}
Your misunderstanding something, the list of hospitals (as mentioned) should not be inside your hospital class. You have to consider your hospital class as a blueprint you are using in your application.
Which means that you need to have a list of hospitals, as a list inside your other application class (which runs the application) and the InsertHospitals method should not be in your hospital class either obviously.
As you add a new hospital in your program, you create a new hospital object and add it to the list of hospitals (fx an arraylist) your keeping as a field value.
Also posssibly make a new constructor with parameters in the hospital class so you can insert the values outside of the class.
Something like this fx.
public class MainApp {
private ArrayList<Hospital> hospitalList;
public static void main(String[] args) {
// Initialize or load it from a file or whatever here.
hospitalList = new ArrayList<Hospital>();
// your code here...
}
public void insertHospital(<insert parameters here to create a hospital>) {
Hospital newHospital = new Hospital(<insert params with new constructor>);
hospitalList.add(newHospital);
}
}
Whatever your problem, your program completely wrong. In insertHospital() your changing Name and Departments fields, and creating new Hospital with those values. When you print Hospital information all hospitals will have the same value.

Storing multiple object types in a List

I have following homework about computer store:
There are several class include: Monitor, Case, Mouse, Keyboard.
All the classes have common fields: id, name, price, quantity.
Each class has some unique fields.
All most features are: add, update, delete, find, show list, save, load file
-So, first I will create a class named Product have 4 common fields. Above classes will extends from Product.
-Then, I think I maybe create a ComputerStore class which have a field is items type ArrayList. items stores all objects which are instance of 4 above classes But I'm not sure.
Whether it is reasonable? I need some ideas
Before , I always use ArrayList store for only one class like
List <String> list = new ArrayList<String>();
Now they are multi type. I think it's generic in Java, right??
In case, I want to update for 1 items. I must think about how to change information for them. Ex: mouse for some code, keyboard for another code. Anyway, thank for everybody!
Your approach is 100% reasonable.
You are completely on the right track with "generics". First, check out the official enter link description here.
Next, just think about your data in real world terms, like you are already doing: Monitor, case, mouse, and keyboard are products. Your computer store's inventory is a list of products.
Hint: A list of products.
Put that together with what you learn about generics through that tutorial, and you'll be good to go.
You could use java generic.First create a java collection (ex: List) with supper class type, Product. Now you could add any sub classes (Monitor , Keyboard etc) in your collection (List) that extends of class Product.
public class Product{
}
public class Monitor extends Product{
}
public class Keyboard extends Product{
}
List<Product> products = new ArrayList<Product>();
products.add(new Monitor());
products.add(new Keyboard());
Since you have a superclass (Product), you can have the list's type as Product, i.e.
List<Product> list = new ArrayList<Product>();
list.add(new Mouse());
list.add(new Keyboard());
It will allow you to iterate them and list their name and price without caring for the class, but if you intend to take an item out of the list you'll need to check its actual type (depending on what you do with it).
You can do like below
import java.util.List;
import java.util.ArrayList;
class Test{
public static void main(String... args){
List<MultiObj> multiObjs = new ArrayList();
MultiObj ob = new MultiObj(); multiObjs.add(ob);
ResX xOb = new ResX(); multiObjs.add(xOb);
ResY yOb = new ResY(); multiObjs.add(yOb);
ResZ zOb = new ResZ(); multiObjs.add(zOb);
for (int i = 0; i < multiObjs.size(); i++ ) {
System.out.println(multiObjs.get(i).getV());
}
System.out.println("Waoo its working");
}
}
class MultiObj{
public String greet(){
return "Hello World";
}
public String getV(){
return "Hello World";
}
}
class ResX extends MultiObj{
String x = "ResX";
public String getX(){
return x;
}
public String getV(){
return x;
}
}
class ResY extends MultiObj{
String y = "ResY";
public String getY(){
return y;
}
public String getV(){
return y;
}
}
class ResZ extends MultiObj{
String z = "ResZ";
public String getZ(){
return z;
}
public String getV(){
return z;
}
}
You could do this:
public class Item {
public Item(int id, string name, float price, int amount, int ArrayID) {
if (ArrayID == 1) {
ID1 = id;
name1 = name;
price1 = price;
amount1 = amount;
}
if (ArrayID == 2) {
ID2 = id;
name2 = name;
price2 = price;
amount2 = amount;
}
if (ArrayID == 3) {
ID3 = id;
name3 = name;
price3 = price;
amount3 = amount;
}
if (ArrayID == 4) {
ID4 = id;
name4 = name;
price4 = price;
amount4 = amount;
}
}
//ArrayID #1
public static int ID1;
public static String name1;
public static float price1;
public static int amount1;
//ArrayID #2
public static int ID2;
public static String name2;
public static float price2;
public static int amount2;
//ArrayID #3
public static int ID3;
public static String name3;
public static float price3;
public static int amount3;
//ArrayID #4
public static int ID4;
public static String name4;
public static float price4;
public static int amount4;
public static int[] id = ID1, ID2 ID3, ID4;
//so forth...
}

Creating a simple stock inventory program - 2nd attempt

I have asked this question before and followed the feedback as best as I could but I am still having one problem with storing the info that the user enters into the array.
Here is the first attempt:
OOP Java: Creating a stock inventory program
So I need to have in total three classes(That's required). The Stock, stock inventory and then the user interface. The purpose of this program is to ask the user to input the company's name, stock rating, price and the number of shares. Of course, I then have to do other things. I think I am okay with the rest, the problem is the stockInterface, the last bit of code that I post below.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
public class StockInterface() {
private static StockInventory stockPortfolio;
public static void main (String [] args){
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
This piece of code doesn't work.
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares)
Can somebody please show me the proper way to store the info into the array? Thank you very much.
Lots of compile errors...
You have defined stockRating as a String but yet return it as an int:
public int getStockRating() {
return stockRating;
}
The same is true for price.
You have extra parenthesis here:
public class StockInterface() {
^
Also in StockInventory, there are multiple statements in the class block They belong in a method.
console is not instantiated.
stockPortfolio is assigned as an array entry, yet it is a single object, and assigned to the Stock which is not a matching type.
So you've declared the stockPortfolio as an instance of StockInventory. StockInventory is a class not an array, so you can't use stockPortfolio [0] = ... because stockPortfolio is an instance of the class. You have a private member in StockInventory that is an array of Stock class instances. What you need is an accessor method to be able to manipulate it. So change StockInventory as follows:
public class StockInvetory {
/*
All the code you have now ...
*/
public Stock [] getStocks(){
return stocks;
}
public setStocks(Stock [] value){
//maybe some checking here ...
stocks = value;
}
}
Now just a slight change in using the class. You need to use the accessor methods as follows:
public class StockInterface {
/*
What you have just the following line changes ...
*/
stockPortfolio.getStocks()[0] = new Stock(stockName, stockRatings, stockPrice, numberShares);
}
I am assuming you are happy with the way you are initializing the array and that you have decided arrays are better than more dynamic data structures in collections for your specific project. If this is not true have a look at Java Collections they may bring you more joy.

Categories

Resources