Creating multiple instances of a class in java - 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);
}

Related

How to add an object with multiple fields into an ArrayList?

I'm fairly new to Java and I've been trying to add an object to an ArrayList storing the respective object type. However, there is a catch. I want to have an indefinite amount of objects added into the ArrayList. The length is based on the user input, so I can't define them beforehand and use .add() after initializing the fields.
This is the class in question. There are 4 private fields and public getters and setters (only two included for context):
public class Player {
private int id; // This will be unique for each player.
private int roundScore; // Score accumulated during a round, suspect to be reset if the player rolls a double.
private int bankScore; // Secured score of a player.
private String name;
public Player() {
roundScore = 0;
bankScore = 0;
}
public void setID(int id) {
this.id = id;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
And this is the method I tried to use to generate players (this method is in another class):
public void generatePlayers(int num) {
Player dummyPlayer = new Player();
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // Oops, this is dumb.
}
}
The idea was to create an instance of a player object called "dummyPlayer", store the variables into the object and add the object into the ArrayList. "Should be fine, right?" or so I thought before I realized I basically added multiple instances of the same object which will all change if I change one of them because referencing is a thing.
Is there a way to individually set the fields of each value in the array? I'm sorry if I missed something vital or asking something stupid. I tried to search other questions but they didn't quite click. Thank you for your time.
As commented by #tgdavies, change generatePlayers() to move the new Player() line inside the for loop like so:
public void generatePlayers(int num) {
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
Player dummyPlayer = new Player();
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // Oops, this is dumb.
}
}
This way for every iteration of the for loop you create a new instance of Player, and you get to keep the as-is dummyPlayer variable (since local variables only exist within the block it is stated).
If for some reason there is a need to reference the dummyPlayer variable outside the for loop, you can state just the type and variable name before the loop and instantiate the Player class in the loop:
//... Same as above
Player dummyPlayer; //beware of null
for (int i = 0; i < num; i++) {
dummyPlayer = new Player(); //Player class instantiation
//... Same as above
}
dummyPlayer.toString(); //you can still reference dummyPlayer from here

How to represent ranges in while statments?

I am writing a small game for fun that uses an action system for multiple teammates.
I do not know how to represent the range of all members 0-9 in an array in a while loop.
I know that, there is a way to do closedOpen, but I don't know how that would fit into the code.
int[2][10][0] hea //Using two teams, each with 10 members, who have multiple traits
// ^ I know this isn't perfect syntax
while (hea[0][0-9][0]!=0){ // Tests for if at least one member of team has actions
Actions
}
// Is there a way to represent the middle step in the array without typing out all and statements
How about a for loop?:
for (int i = 0; i < hea.length; i++) {
int[][] team = hea[i];
for (int member = 0; member < team.length; member++) {
int[] traits = team[member];
//Check actions
}
}
Speaking from a game design perspective, I would not shy away from using classes for things like this:
public class Team {
private final List<Player> players = new ArrayList<>();
public static final int MAX_SIZE = 10;
}
public class Player {
public String getName();
public List<Action> getActions();
}
public class Action {
private final int[] basic; //however you wish to implement
}
public class Game {
private final List<Team> teams = new ArrayList<>();
public void addPlayer(Player player);
}
Check out the Oracle Java Tutorials for a more in-depth explaination on learning java.
One of the most direct ways is to write a (private) method to do the checks all over the array. Something like:
/** Tests if at least one member of the team has actions left */
private boolean haveActionsLeft(int [][][] hea, int team, int members) {
for (int m = 0; m < members; m++) {
if (hea[team][m][0] >= 0) {
return true;
}
}
return false;
}
And then you can call the function into your while statement's condition:
...
while (haveActionsLeft(hea, 0, 10)) {
Actions
}
If I'm not mistaken by your intent, this is the perfect use case for a for loop
A for loop takes a value and increments (or decrements) it and is a good way to iterate through a fixed number of options.
for(int i = 0; i < 9; i++) {
if(hea[0][i][0] != 0) {
Actions
}
}
This says: start i at 0, and go through the loop. At the end of the loop, increment i. continue until i reaches 9 and then break the loop.

Accessing Objects Made in Array from Different Class

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...

String and Int arrays not being initialized to right values

So what I'm trying to do here is initialize my strings to an empty string and my ints to 0. The display report is kind of a debugger at the moment, and when I run the program that calls displayReport, it only displays my ints and strings as null. It has to be something in my for loop, but I can't seem to figure out what I am doing wrong.
EDIT: To be clear, I HAVE to use private void initializeString(String[] s) and private void initializeInt(int[] a). And my constructor has these guidelines
public constructor: Initializes arrays holding soft drink name and ID to hold all empty strings (calls intitializeString twice to perform the tasks). Initializes arrays holding starting inventory, final inventory, and the counts of the number of transaction to zero (calls initializeInt three times to perform the tasks).
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class SoftDrinkInventory {
static final int MAXSIZE = 100; // maximum size of 100
private String[] names; // softdrink names
private String[] ids; // softdrink identifications
private int[] startingInventory; // starting inventory of the softdrinks
private int[] finalInventory; // final inventory of the softdrinks
private int[] transactionCounts; // number of transactions per softdrink
private int trueSize; // total number of softdrinks
/**-----------------------------------------------------------------------
* constructor
*
* Initializes arrays holding soft drink name, ID number to the
* empty string. Initializes starting inventory, final inventory,
* and transaction counts are to zero.
*/
public SoftDrinkInventory() {
initializeString(names);
initializeString(ids);
initializeInt(startingInventory);
initializeInt(finalInventory);
initializeInt(transactionCounts);
}
/**-----------------------------------------------------------------------
* displayReport
*
* Displays a report including soft drink name, ID, starting inventory,
* final inventory, and number of transactions processed.
*/
public void displayReport() {
System.out.printf("%-22s %-16s %-23s %-23s %s %n", "Soft Drink", "ID",
"Starting Inventory", "Final Inventory",
"# transaction");
for(int i = 0; i < 10; i++) {
System.out.printf("%-22s %-16s %-23f %-23f %f %n", names, ids,
startingInventory, finalInventory,
transactionCounts);
}
}
/**-----------------------------------------------------------------------
* initializeInt
*
* Takes an int array parameter and initializes its array values to zero.
* #param a int array
*/
private void initializeInt(int[] a) {
a = new int[MAXSIZE];
for(int i = 0; i < a.length; i++) {
a[i] = 0;
}
}
/**-----------------------------------------------------------------------
* initializeString
*
* Takes a String array parameter and initializes its array values to
* the empty string.
* #param s string array
*/
private void initializeString(String[] s) {
s = new String[MAXSIZE];
for(int i = 0; i < s.length; i++) {
s[i] = "";
}
}
}
Java uses pass by value. This means the references you pass in are being modified, not the originals. The simplest solution is to return the array you want.
names = initialiseString(100);
However, a better approach is to use a List of Objects like
private final List<Item> items = new ArrayList<>();
// to add
items.add(new Item("name", "id", 1234, 10, 1224));
// you can add any size 0 up to 2 billion.
int actualSize = items.size();
class Item {
private String name; // softdrink name
private String id; // softdrink identification
private int startingInventory; // starting inventory of the softdrink
private int finalInventory; // final inventory of the softdrink
private int transactionCount;
}
You can't overwrite a reference, that was passed as an argument to a method, inside that method. When you're doing a = new int[MAXSIZE]; you are creating an array that is visible only to that method. What you need to do is return the created array. You might consider doing something like this:
private int[] initializeInt(int size) {
...
}
...
startingInventory = initializeInt(MAXSIZE);
Because you are initializing the arrays local to those initializing methods. Instead of passing argument to the methods, simply create and initialize a new array within the methods and return those arrays to respective instance variables.
For example change your initializeString(String[]) to public String[] initializeString() and within this method write.:
String[] names = new String[MAXSIZE];
for(int i = 0; i < names.length; i++) { names[i] = "";} return names;
And then call this method within your constructor as follows
names = initializeString();
There are Java functions that take an array as a parameter, put data in the array, and it is available to you.
For example:
BufferedReader.read(char[] cbuf, int off, int len)
However, you must first create the array, and it just fills it. So you must first do this before calling that function:
char[] cbuf = new char[100];
Since your methods are initializing arrays in the same class, you can just do Vishal K said, and not pass the arrays to the methods. In situations where you are calling methods elsewhere, you can pass objects as parameters to methods in other classes as long as you create the object first. The callee can use the passed reference to modify your object.
Of course there are better ways to do this (such as using List of Objects, as suggested by Peter Lawrey), but since this is in the specs you have, you can try this: when you declare your arrays, also allocate memory for them :
private String[] names = new String[MAXSIZE]; // softdrink names
private String[] ids = new String[MAXSIZE]; // softdrink identifications
private int[] startingInventory = new int[MAXSIZE]; // starting inventory of the softdrinks
private int[] finalInventory = new int[MAXSIZE]; // final inventory of the softdrinks
private int[] transactionCounts = new int[MAXSIZE]; // number of transactions per softdrink
Then, in your functions, you can simply assign values to 0 and empty String:
private void initializeInt(int[] a) {
for(int i = 0; i < a.length; i++) {
a[i] = 0;
}
}
and
private void initializeString(String[] s) {
for(int i = 0; i < s.length; i++) {
s[i] = "";
}
}
Please note that you have an error in your displayReport() function too. You are using %f to display int values (%f is used for floats). Instead, change it to %d. Also, in your for loop, you are not actually looping through your arrays. Just use i as an index when iterating. Another thing is that you are displaying only 10 entries, whereas your MAXSIZE, which you use to initialise arrays is 100, so if you want to display all array elements, change 10 to MAXSIZE:
public void displayReport() {
System.out.printf("%-22s %-16s %-23s %-23s %s %n", "Soft Drink", "ID",
"Starting Inventory", "Final Inventory",
"# transaction");
for(int i = 0; i < MAXSIZE; i++) {
//change "%-22s %-16s %-23f %-23f %f %n" to the below
//and names etc. to names[i] etc.
System.out.printf("%-22s %-16s %-23d %-23d %d %n", names[i], ids[i],
startingInventory[i], finalInventory[i],
transactionCounts[i]);
}
}

Accessing 2-dimensional array from an object class.

In Java I have a 2-dimensional array of objects but I can't access any of those array of objects in the object's class methods. What should I do?
Here's my class:
class GoPiece
{
final int boardSize = 19;
final int empty = 0;
final int black = 1;
final int white = 2;
int pieceType = empty;
int leftRight;
int downUp;
int turnPlayed;
boolean legal;
// GoPiece's Constructor with 3 parameters.
GoPiece(int blackOrWhite, int horizontalCoordinate, int verticalCoordinate)
{
pieceType = blackOrWhite;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
if ((true));
}
// GoPiece's Constructor with 2 parameters.
GoPiece(int horizontalCoordinate, int verticalCoordinate)
{
pieceType = empty;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
}
// GoPiece's Constructor with no parameters.
GoPiece()
{
leftRight = 0;
downUp = 0;
}
// Initialize an empty Go board full of GoPieces.
GoPiece[][] InitializeBoard()
{
GoPiece[][] intersection = new GoPiece[boardSize][boardSize];
for(int horizontal = 0; horizontal < boardSize; horizontal++)
{
for(int vertical = 0; vertical < boardSize; vertical++)
{
intersection[horizontal][vertical] = new GoPiece(horizontal,vertical);
}
}
return intersection;
}
// Make a piece a certain type: empty, black, or white.
public void SetType(int newType)
{
pieceType = newType;
}
public int GetType()
{
return pieceType;
}
public void CheckKill()
{
int foobar = this.GetType();
}
}
I can then use InitializeBoard() in another part of my program to create a two dimensional array of GoPieces... this works, but How do I access all of those pieces other than the one I'm referencing in the class GoPiece's member functions? I tried passing the whole array into one of GoPieces functions, but that didn't seem to work.
Go is an Ancient Chinese Board game. The CheckKill() method above is where I tried to access different parts of the array, but failed. Here I have some working dummy code.
Thank you.
You need to create a separate class to represent the board itself (including the current placement of pieces). The logic for creating a board, testing for a kill, etc., belong to the board, not to an individual piece.
Do you mean you want to call a method with the array like InitializeBoard.GetType(); Where InitializeBoard is a 2 Dimensional Array?
You can't do that. You Must Specify which GoPiece to get out of InitializeBoard. Example: InitializeBoard[0][0].GetType(); If you must call all methods, you can use a for loop to call each individually.

Categories

Resources