Accessing 2-dimensional array from an object class. - java

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.

Related

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.

Returning a 2-Dimensional Array from a method

I'm trying to return a 2-dimensional array from a function inside of a class. I don't want to create a new array inside the function because I want to return the same one I've passed into the function.
I've tried creating a new array with the same name, but it says it's already defined within the scope. I've also tried just doing (return plane;) which doesnt work because of incompatible data types. I've also tried (return plane[][];) but that doesnt work either.
public class Airplane {
private String maxSeats; //used for constructor
private char[][] plane = new char[13][6]; //array to be passed in
public char create(char[][] plane) {
plane[13][6]; //this is where I'm unsure what to do
//initialize them as '*' to start
for (int i = 0; i <= 12; i++) {
for ( int k = 0; k <= 5; k++) {
plane[i][k] = '*';
}
return plane;
}
}
I'm trying to return the array to be used in another function where I will modify it.
You have to change the return type to char[][] since you want to return a 2-dimensional array of characters and not just a single character
public class Airplane {
private String maxSeats;
private char[][] plane = new char[13][6];
public char[][] create(char[][] plane) {
// plane[13][6]; you should remove this line, it's the wrong syntax
//and it's unneeded since you've already declared this array
// this is a more compact version of your nested loop
for (int i = 0; i < 13; i++) {
Arrays.fill(plane[i], '*'); //fills the whole array with the same value
}
return plane;
}
}

Assigning Strings to field of Partially Filled Array

I have a text file that contains about 80000+ words. I'm trying to check the length of these words and see if it matches a number entered without using an Array Lists.
Say that an array has these global variables:
public static int INITIAL_SIZE = 100;
public static int size;
public String[] array = new String[INITIAL_SIZE];
I'm going to create an object:
PartArray part = new PartArray();
And a field:
part.array = new String[INITIAL_SIZE];
(And then proceed to expand the array with another method by multiplying the initial size by 2 until it can contain all 80000+ words)
But I want to assign every word in the array at 0, 1, 2, ..... (80000 -1) to something of the extent;
part.array[part.size++] = "aardvark";
.....
part.array[part.size++] = "zymurgy";
so that I can print the words that have this specific length.
part.array[0];
But how would I do that? Should I create another class in java? I just don't want to put "String" in front of every word in that text file.
I am not totaly sure if I understood what you were trying to do, but from what I understand, you want to implement something similar to an ArrayList..
First let's clarify something. The code example you posted will always result in an ArrayIndexOutOfBoundsException:
part.array[part.size++] = "aardvark";
.....
part.array[part.size++] = "zymurgy";
No matter how big your array is, you'll try to access memory, which is outside of that array.
If you really do not want to use an ArrayList (or any other List), you might want to create your own class which behaves in a similar way..
public class StringList{
public static final int DEFAULT_INITIAL_SIZE = 100;
public static final float DEFAULT_SCALE_FACTOR = 2;
private String[] content;
private float scaleFactor;
private int counter = 0;
public StringList(){
this(DEFAULT_INITIAL_SIZE);
}
public StringList(int initialSize){
this(initialSize, DEFAULT_SCALE_FACTOR);
}
public StringList(int initialSize, float scaleFactor){
this.scaleFactor = scaleFactor;
content = new String[initialSize];
}
public void add(String toAdd){
//check if we ran out of space for new content..
if(counter == content.length){
//create a new array with twice the current arrays size
String[] temp = new String[(int) (content.length * scaleFactor)];
//efficiently copy content from current array to temp
System.arraycopy(content, 0, temp, 0, content.length);
content = temp;
}
content[counter++] = toAdd;
}
public String get(int index){
return content[index];
}
public int size(){
return counter;
}
}
That class should do everything you need..
Here a short example..
StringList stringList = new StringList();
stringList.add("aardvark");
// add more stuff...
stringList.add("zymurgy");
for (int i = 0; i < stringList.size(); i++) {
String someText = stringList.get(i);
// do stuff with your string...
}

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);
}

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