Acces linked list in main class from another class java - java

I have this project of an Online Store. The class OnlineStore is where the main method is, that starts the program. I also have 3 classes, User, Item andPackage, with some inherited classes.
I store all users, items and Packages in linked lists.
I created instances in the class OnlineStore inside the main method but I want to be able to access to them every moment; The class Item sould be able to access this linked list and remove an item that has been sold.
public class OnlineStore{
public static void main(String[] args) {
LinkedList<User> users = new LinkedList<User>();
LinkedList<Item> itemsSold = new LinkedList<Item>();
LinkedList<Item> items = new LinkedList<Item>(
LinkedList<Package> packages = new LinkedList<Package>();
}
}
//Then I create some instances of Items Users and call their methods of buying,
//loging in, etc..
//If a item is buyed:
public class Buyer extends User {
//ATTRIBUTES
private String accountNumber;
private LinkedList<Item> boughtItems;
//CONSTRUCTOR
public Buyer(String n, String id, String pass, String a){
super(n, id, pass);
accountNumber = a;
}
//METHODS
public void buy(Item i){
boughtItems.add(i);
//Here I need to acces the first class and remove from availableItems
items.remove(i);
}
}
Thanks for your help!
John R.

Try something like this:
public class OnlineStore{
public static LinkedList<User> users = new LinkedList<User>();
public static LinkedList<Item> itemsSold = new LinkedList<Item>();
public static LinkedList<Item> items = new LinkedList<Item>();
public static LinkedList<Package> packages = new LinkedList<Package>();
public static void main(String[] args) {
}
}

Related

Converting an Object list to a Queue

How do I convert a List of objects to a Queue and still be able to access their variables?
First I have a main class that creates instance classes of ClassTwo and gives them a unique ID (just hard coded it for the example)
public class ClassOne
{
static List<ClassTwo> processList = new ArrayList<ClassTwo>();
public static void main(String[] args)
{
processList.add(new Process(1));
processList.add(new Process(2));
processList.add(new Process(3));
}
}
ClassTwo:
public class ClassTwo
{
int id;
public ClassTwo(int tempID)
{
id = tempID;
}
}
How would I convert my List to a Queue so that I can still access each object's ID in class one?
I tried something like:
public class ClassOne
{
static List<Process> processList = new ArrayList<Process>();
public static Queue<Object> processQueue = new LinkedList<Object>();
public static void main(String[] args)
{
processList.add(new Process(1));
processList.add(new Process(2));
processList.add(new Process(3));
ConvertToQueue();
}
ConvertToQueue(List<Process> process)
{
//covert here..
}
}
but I'm not sure exactly how to then convert it to a Queue, so i can still call variable 'id' from each ClassTwo object. Help would be appreciated!
You can use this :
Queue<Process> queue = new LinkedList<>(processList);
When you make this, you can still access to every element of the list, because they are all the same instances.

Instantiate objects using a helper class

I want to create an instance of my object, car. The problem I have is that i can create an instance of the car object such as, Car car1 = new car("Audi","A4","BF10YMR"); however I want to create car objects through a helper class. How do I call this helper class in main so that is of type car and not of type carHelper?
The car object requires a random registration number to be created and this is created in the carHelper class. The object is returned.
public class Car implements Comparable<Car>
{
public class Car
{
private String make;
private String model;
private String registration;
public Car(String make, String model, String reg)
{
this.make= make;
this.model= model;
registration = reg;
}
}
public class carHelper
{
public car genCar()
{
String reg = //some method to generate random registration.
String Make = //some method to randomly pick make from a list
String model = //some method to randomly pick model from a list
return new Car(make,model,registration);
}
}
public class Garage
{
public static void main (String args[])
{
Garage MyGarage = new Garage();
Car car1 = new Car("Audi","A4","BF10YMR") //works, but doesn't use helper
Car car2 = carHelper.genCar(); // something like this?
carHelper c = new carHelper(); // thought something like this but
System.out.println(c.genCar()); // creates object of type carHelper
// not car.
MyGarage.add(car1);
MyGarage.add(car2); // gives me carHelper cannot be converted to Car
}
}
public class GarageOp implements CarList
{
public GarageOp()
{
list = new ArrayList<Car>();
}
public boolean add(Car car)
{
if (list.contains(car) == false)
{
list.add(car);
return true;
}
}
}
Expected result is create car object using the helper class and add it to an ArrayList.
You could create this lists in the CarHelper and than, randomly, select the values and create a new Car with them. The UUID creates a random 128 bits (including hex) number and converts to a String
public class CarHelper {
private List<String> makeList = Arrays.asList("s", "t", "f", "n");
private List<String> modelList = Arrays.asList("yyt", "32g", "dc3", "aas");
public Car genCar() {
String reg = UUID.randomUUID().toString();
String make = makeList.get(new Random().nextInt(makeList.size() - 1));
String model = modelList.get(new Random().nextInt(modelList.size() - 1));
return new Car(make,model,reg);
}
}
Make the genCar() method as Static in the CarHelper class.
public car static genCar(){
// do stuff to create object
}
a non-static method can access a static variable or call a static method in Java.

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.

Arraylist Java Binding errors

I need to create my own registry for a school project.
I would like to have
1
room, room
2
room, room
hall, hall
3
room, room
hall, hall
dorm, dorm
But all I am getting is
1
room,room
2
room,hall
hall,hall
3
room,dorm
hall,dorm
dorm,dorm
So somehow the the facility reference got changed somewhere but i have no idea how to fix this. Can anyone help?
These are my codes.
public class registry {
static List<registryRecord> register = new ArrayList<registryRecord>();
public static boolean bind(String name, facility ref){
for(registryRecord r:register){
if(r.name.equals(name)) //check if the name is already binded
return false;
}
registryRecord newRecord = new registryRecord(name, ref);
register.add(newRecord);
for (registryRecord r:register){
System.out.println(r.name +","+ r.ref.name);
}
return true;
}
public class registryRecord {
String name;
facility ref;
public registryRecord(String name, facility ref){
this.name = name;
this.ref = ref;
}
public class server {
public static void main(String args[]) throws Exception{
facility room = new facility("room");
System.out.println(1);
boolean test = registry.bind("room", room);
facility hall = new facility("hall");
System.out.println(2);
boolean test2 = registry.bind("hall", hall);
facility dorm = new facility("dorm");
System.out.println(3);
registry.bind("dorm", dorm);
}
public class facility {
public static String name;
static List<booking> bookings;
public facility(String name){
this.name=name;
this.bookings = new ArrayList<booking>();
}
}
As I suspected, since name is static in facility, it is shared between all instances. This means that it gets overwritten each time you create a new instance.
Just remove static from both your fields, and your program should work fine.

Java - Passing Arrays in Methods, Variables Not Recognized

I have been stuck on this one for days, but I have broken it down here. What I need to do is to create an array of accounts with about 9 variables each (AccountID, WithdrawlDates, etc.) that the user can input in a command prompt. From the createAccount() method I can send an instance of user and a accountNum, but the user is not recognized on the receiving setAccount method.
Here's the code:
class User{
private int accountID;
User( int id )
{
accountID = id;
}
static void setAccountID(User user[], int accountNum)
{
user.accountID = accountNum; //accountID is not recognized here
}
static void getAccountID(User user){System.out.println(user.accountID);}
}
class TestUser
{
public static void main(String[] args)
{
createAccount();
}
static void createAccount(){
User[] user = new User[2];
user[0] = new User(25);
User.setAccountID(user, 2001);
}
}
I am open to changing the flow of this, but I don't know where to start.
Thanks!
To access the elements of an array instead of doing something with the array itself you use square brackets like so:
user[userIndex]
from there you can either change the element like this
user[userIndex] = new User(id);
or access/modify something about the element itself like this
user[userIndex].accountID = whatever;
Additionally, your use of static in the setAccountID is confusing things. A static method cannot know anything about accountID because accountID is a part of a uniquely created object where the static method belongs to the class, and not any particular object. If it must be static for some reason, you will need to change the method to look something like this
static void setAccountID(User user[], int userIndex, int accountNum)
{
user[userIndex].accountID = accountNum;
}
but the following would be much better, since you know the user inside the array anyway:
void setAccountID(int accountNum)
{
this.accountID = accountNum;
}
called like this:
user[userIndex].setAccountID(accountNum);
There's no reason to pass an array of User objects. Try this instead:
class User{
private int accountID;
User( int id )
{
accountID = id;
}
static void setAccountID(User user, int accountNum)
{
user.accountID = accountNum; //accountID is not recognized here
}
static void getAccountID(User user){System.out.println(user.accountID);}
}
class TestUser
{
public static void main(String[] args)
{
createAccount();
}
static void createAccount(){
User user = new User(25);
User.setAccountID(user, 2001);
}
}
EDIT: If you need to maintain an array of users as #Luiggi Mendoza suggests in his comment, just pass a single array element to setAccountID():
static void createAccount(){
User[] user = new User[2];
user[0] = new User(25);
User.setAccountID(user[0], 2001); // set id for first User
}

Categories

Resources