Accessing Objects Made in Array from Different Class - java

i am having trouble trying to figure out how to access objects that were made in an array in another class from Main. Psuedo for what im trying to do.
In Main CLass Prompt user for number of Tables In the Restaurant
take number n, create array of n Table objects in Restaurant Class
Access each tableobject created and be able to add values to it via constructor all from main
Hopefully the code can Explain Better.
My Main Class
Restaurant RestaurantObject = new Restaurant();
Table TableObject = new Table();
System.out.println("Max Tables In Restaurant? (Interger)");//Set Max Tables
Scanner smax_tables = new Scanner(System.in);
int max_tables = smax_tables.nextInt();
RestaurantObject.create_table_array(TableObject, max_tables);
My Restaurant Class
private Table[] TableList; //and other random variables
//other methods
public void create_table_array(Table table,int number) {
Table[] TableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++) {
TableList[i] = table;
}
public Restaurant() {
}
My Table CLass
int max_amount;
public int getMax() {
return max_amount
}
Table(int number) {
this.max_amount = number;
}
And my desired action
run program and enter 5 for max tables
5 tables created in restaurant
RestaurantObject.Table1(10) //set max to 10 in table object
System.out.printf("max amount for table1 is %d",Restaurant.Table1.getMax()
Now that im re-looking at it. Would i have to prompt the user for the table to edit, get and return that table object in the array? Any help would be great,thanks

If i get your question right, the you want to access the array created here :
public void create_table_array(Table table,int number) {
Table[] tableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++)
tableList[i] = table;
}
What you can do is change the method from void to Table[] and return the created array. Like this:
public Table[] create_table_array(Table table,int number) {
Table[] tableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++)
tableList[i] = table;
return tableList;
}
Now in your main program, you can call the method like this:
Table[] tables = RestaurantObject.create_table_array(TableObject, max_tables);
Now you can access all tables by their indices. For example
for(int i = 0; i < tables.length; i++)
//do something to tables[i]
Also, you should stick with JAVA naming conventions and use camelCase for variable names. For example: TableList==>tableList etc...

Related

a set indexed objects in ArrayList - is it possible?

Is it possible to create a set indexed objects in ArrayList?
I want to create an array of objects - Portal class - and have them indexed in array which size will be defined by user.
import java.util.ArrayList;
import java.util.Scanner;
public class GameFunctions
{
Scanner sc = new Scanner(System.in);
private int portalsQty;
private String[] portalNamesDB = {"name1", "name2", "name3", "name4", "name5"};
ArrayList<Portal> portals = new ArrayList<>();
void setPortalsQty(int portalsQty)
{
this.portalsQty = portalsQty;
}
int getPortalsQty(int portalsQty)
{
return portalsQty;
}
private void createPortals()
{
System.out.println("type the
amount of portals");
portalsQty = sc.nextInt();
System.out.println("number of portals: " + portals.size());
for (int i = 0; i < portalsQty; i++)
{
portals.add(i,p[i]); // CANNOT HAVE VALUES INDEXED LIKE p[i] IN ARRAYLIST
}
}
private void namePortals()
{
int randomNo = (int)(Math.random()*portalsQty);
for (int i = 0; i < portalsQty; i++)
{
System.out.println("Random: " + randomNo);
portals[i].setPortalName(portalNamesDB[randomNo]);
}
}
public void launchGame()
{
createPortals();
namePortals();
}
}
Defining the size of array by user makes using tables not feasible, as we encounter NullPointerException.
Is there any other solution to make dynamic size of the table and have the elements indexed?
import java.util.HashMap;
HashMap<Integer, portal>portals = new HashMap<>();
System.out.println("number of portals: " + portals.size());
for (int i = 0; i < portalsQty; i++)
{
int randomNo = (int)(Math.random()*portalsQty);
portals.put(portalNamesDB[randomNo], i);
}
Mureinik and chrylis are right, a map, or HashMap would probably work best here.
I added an example of how you could implement it. This way you are giving each portal a name and quantity value all in one for loop. The portal name is the key, and the quantity number is the value in my example.
I hope that helps!
You could emulate this behavior with a map that maps from the index to the object:
Map<Integer, Portal> indexes = new HashMap<>();

Creating multiple instances of a class in java

Right so i have got this class called PlaneSeat,
the constructor in another class called PlaneSeat is
public PlaneSeat (int seat_id){
this.seatId = seat_id;
}
1) I wish to create 12 instances of this class with each PlaneSeat having a seatID of 1-12
Should i do this: (I dont know what this does)
private int PlaneSeat;
PlaneSeat [] seats = new PlaneSeat[12];
or (I dont know what this does either)
private int PlaneSeat[] = { 1,2,3,4,5,6,7,8,9,10,11,12};
Which one is better and what does what?
2) Also, if i have another class where the main is found and i wish to access the seat ID of each seat on the plane, how should i do it?
jet1.getSeatID // doesnt work where jet1 is a instance of a plane
2) To access seatID, you need an accessor (normally called getSeatID()) in the PlaneSeat class.
public int getSeatID () {
return seatID;
}
1) private int PlaneSeat; PlaneSeat [] seats = new PlaneSeat[12];
You don't need to declare private int PlaneSeat, which doesn't actually make sense. Should be private PlaneSeat seat; or something... PlaneSeat[] seats = new PlaneSeat[12]; creates a new array of PlaneSeat objects with a size of 12.
private int PlaneSeat[] = { 1,2,3,4,5,6,7,8,9,10,11,12};
Again, this should be private PlaneSeat[] seats;
To create your seats, you would first declare your seat array
PlanetSeat[] seats = new PlaneSeat[12];
Then you can use a loop to fill the seats:
for (int i = 1; i <= 12; i++) {
seats[i-1] = new PlaneSeat(i);
}

searching by last name in an array

I made a contact list with three classes, the ContactList class holds an array which stores Last Name, First Name, Street, City, State, ZIP, Country, Email, Phone No., and Notes.
I want to implement a search function by last name into the class of ContactList, where it shows all the information of the contact who has the last name the user searched for, but i cant seem to get anything to work. :(
import java.util.*;
public class ContactList {
//declaration of an array and its attributes
private final int SIZE = 10;
private Person [ ] list;
private int nextEmptyElementInArray = 0;
// Constructor for ContactList object
public ContactList () {
list = new Person [SIZE];
}
// Method that adds a new contact into the array
public void addNewContact() {
list[nextEmptyElementInArray] = new Person();
list[nextEmptyElementInArray].read();
nextEmptyElementInArray++;
}
// Method retrieves contacts by last name
int searchByLastName(Person [] list) {
Scanner console;
console = new Scanner(System.in);
String searchByLastName = console.next();
for (int i= 0; i< list.length; i++) {
if (list[nextEmptyElementInArray].lastName.equals(searchByLastName))
return i;
}
return -1;
}
}
Your list subscript appears to be wrong: for each iteration of the loop you're doing this:
if (list[nextEmptyElementInArray].lastName.equals(searchByLastName))
If I understand the question correctly, you should be doing this:
if (list[i].lastName.equals(searchByLastName))
Also, be careful about naming your variable the same as the function. At best it'll cause confusion.
[Edit] Just noticed you're pre-allocating the list, then managing actual content length using nextEmptyElementInArray. Your for loop should probably go something like this:
for (int i= 0; i< nextEmptyElementInArray; i++)
I suggest to change the search method as
int searchByLastName(Person [] list, String lastName) {
for (int i= 0; i < list.length; i++) {
if (list[i].lastName.equals(lastName))
return i;
}
}
return -1;
}
read lastName from console outside this function and pass it as a search param

Java, filling Object[][] array with data

I'm trying to fill an Object[][] array with data from my Object Class. However im having problems filling the array. Below is what I am trying to do to fill the Object[][] data. at the moment the returned data variable cannot be seen by the method. I have tried removing the method and filling the array where rows in declared but cannot because there is a for loop.
Am I currently filling the object[][] array correctly?
public class CustomersDialog extends javax.swing.JDialog {
private CustomerList customers = new CustomerList();
Object rows[][] = getData();
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer = new Customer();
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
Object [][] data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
}
Further doing this method of creating the array outside the loop causes an 'empty statement message' by the compiler and it says it 'requires line ends ; after the .get statements':
public Object[][] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Customer customer;
Object [][] data;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
You're not doing it properly.
In your code, you're declaring an array INSIDE for loop, which means that after the loop, the array doesn't exist anymore. That's why you can't return data - it simply does not exist.
More about scope and lifetime of variables you can read there: http://www.c4learn.com/javaprogramming/the-scope-and-lifetime-of-variables-in-java-programming-language/
What you want to do is to declare array outside the loop:
Object [][] data;
for(int i; i < size; i++) {
// Filling data array
}
return data;
Next thing is that if you want to use an array, you should initialize it first:
Object [][] data = new Object [size][3];
Then you can fill it in for loop, like this:
for(int i; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i][0] = Integer.toString(customer.getCustomerID());
data[i][1] = customer.getfName();
data[i][2] = customer.getlName();
}
You have to allocate the array in two times. Once for the rows, and after once per row.
Object[][] data = new Object[size];
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
data[i] =
new Object[]{
Integer.toString(customer.getCustomerID()),
customer.getfName(),
customer.getlName()
};
}
If you really want to use a 2 dimensional Array than you must define the size of the Array first (also if it is a n dimensional Array!)
See this content to get some clarification:
http://www.leepoint.net/notes-java/data/arrays/arrays-2D.html
It seems to me like you only have one size Parameter for the Array, so I would use a normal Array instead of a 2 dimensional one.
I would do something like this:
public Object[] getData() {
customers = dataManager.getUserData();
int size = customers.size();
Object[] result = new Object[size];
Customer customer;
for(int i = 0; i < size; i++) {
customer = customers.getCustomerAt(i);
result[i] = {
{ Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
return data;
}
If you have to use a 2 dimensional Object Array, than you have to define the second size dimension and fill the array like this:
for(int i = 0; i < sizeDimOne; i++) {
for(int k = 0; k < sizeDimTwo; k++) {
result[i][k] = { { Integer.toString(customer.getCustomerID()), customer.getfName(), customer.getlName() } };
}
}
Hope this is helpful.

Saving the value of an array in a method

I will just post the pseuducode, hope you will understand:
import java.util*.;
main method {
subemethod1();
submethod1() {
Screen input = new Scanner(System.in);
int buy = input.nextInt();
if( buy != 0) {
submethod2();
}
submethod2() {
Screen input = new Scanner(System.in);
int[][]grid = new int [5][6]
int row = input.nextInt();
int col = input.nextint();
grid[row][col] = 1;
Let's assume I typed 1 for row, and 1 for col this time. then grid[1][1] = 1. I want to save the value of grid[1][1] so that next time I enter row 2, col 2 I will have:
grid[1][1] = 1;
grid[2][2] = 1; and so on for whatever row-col combination I type.
lastly I want to return to submethod1, and I want submethod1 to understand that grid[1][1] = 1 and that grid[2][2] also has the value 1; and so on....
Below I am assuming that you are asking about saving value of grid in an instance of program and not between various instances of program calls. if you want to save value of grid between varrious program calls than you will have to store value of grid in some file etc.
instead of creating the array grid inside submethod2(), create it as a class variable and submethod1(), submethod2() as member functions.
create an object in main method and call submethod1() on the object
something like
class ABC
{
int[][] grid = new int[5][6];
submethod1()
{
...
}
submethod2()
{
...
}
public static void main(String args[])
{
ABC abc = new ABC();
abc.submethod1();
}
}
This is a scoping problem. Essentially you're creating a new int[][] variable called grid every time you call submethod2(). Either store it as a class variable, or pass it in and then return it from submethod2() and manually update it yourself (I wouldn't recommend this approach)
Without more context, it's hard to recommend how to decompose your problem into objects, but one solution could be something like the following:
import java.util*.;
public class MainClass {
private int[][] grid;
public static void main(String[] args) {
submethod1();
}
private void submethod1() {
grid = new int[5][6];
Screen input = new Scanner(System.in);
int buy = input.nextInt();
if( buy != 0) {
submethod2();
}
}
private void submethod2() {
Screen input = new Scanner(System.in);
int row = input.nextInt();
int col = input.nextint();
grid[row][col] = 1;
}
}
Best way to deal with such problem is use Object Oriented approach. Remember that's why we use Java.
Create a class GridItem which will have three properties row, column, value. When you store some value create object of GridItem and store it in Global List. You can then iterate over it in any function and access which values were stored.
class GridItem
{
int row;
int column;
int value;
public GridItem(int row, int column, int value)
{
this.row = row;
this.column = column;
this.value = value;
}
//Provide getters only
}
ArrayList<GridItem>items = new ArrayList<GridItem>();
items.add(new GridItem(1, 1, 1));// 1 row 1 col 1 value
items.add(new GridItem(2, 2, 2));// 2 row 2 col 2 value
items.get(0).getRow()// get first
There are several other solutions. e.g Maintain a global array and then expand it. Create list of grids etc but they all are complicated and do more than necessary.

Categories

Resources