How can you make a 2d array object - java

I'm trying to make a static 2D array object. I came up with one where it has to be initialized by the user but for my purposes I want it to be already initialized.
String str;
int temp = 0;
int check = 0;
Plot[][] farm = new Plot[4][3];
ExperimentalFarm p = new ExperimentalFarm(farm);
for (int i = 0; i < farm.length; i++) {
for (int j = 0; j < farm[i].length; j++) {
str = JOptionPane.showInputDialog("Name the crop");
temp = Integer.parseInt(JOptionPane.showInputDialog("What is the yield"));
farm[i][j] = new Plot(str, temp);
}
}
I'm also trying to return an object from a class to the client. For example, I want to get which player did the best. I want to have their name and their score. How do I return that.

Well, you're doing it. Plot[][] farm = new Plot[4][3]; makes a new 2D array (technically, java does not have 2D arrays. At all. What you can do, however, is a 1D array, whose elements are themselves arrays, which is exactly what that does: farm is of type: "An array whose component types are arrays whose component types are Plot objects", and new Plot[4][3] initializes this array to contain 3 sub-arrays, and each sub-array is initialized to contain an array capable of holding 4 plots.
But that just makes room for plots, it doesn't instantiate 12 plot objects, you have to do that yourself. You are doing just that in the code you pasted: That loop structure ends up running the stuff within ("Name the crop", etc) a grand total of 12 times, meaning, new Plot is executed 12 times, you want that to happen.
Here's how to e.g. do it yourself:
Plot[][] farm = new Plot[4][3];
for (int i = 0; i < farm.length; i++) {
for (int j = 0; j < farm[i].length; j++) {
farm[i][j] = new Plot("barren", 0);
}
}

Related

randomly select and delete 2 different items form array

How can I remove the item in an array that is selected by the random?.
Instead of giving me two different items in an array it's just printing the same item selected by the random.
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
String names_rand = names[rand.nextInt(names.length)];
for(int i = 0; i < 2; i++){
System.out.println(names_rand);
}
It's simply because any code outside the for loop won't run again, try this to run the random code every loop to get a new (possible same since it's random) string from the array
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
for(int i = 0; i < 2; i++){
String names_rand = names[rand.nextInt(names.length)];
System.out.println(names_rand);
}
as for deleting the item that would be somehow complicated using a string array as once it's allocated you can't add or delete from it (you can't modify it's size )unless you are willing to make a new temporary array, copy all of its items without the chosen string like this maybe :
String[] names = {"jey", "abby", "alyssa", "cole", "yzabel", "miho"};
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.length); i++) {
int randInt = rand.nextInt(names.length), cpyIdx = 0;
String[] namesTemp = new String[names.length - 1];
for (int j = 0; j < names.length; j++) {
if (j != randInt) {
namesTemp[cpyIdx] = names[j];
cpyIdx++;
}
}
names = namesTemp;
a better version of this complicated code would be using an ArrayList, which allows to add and remove its items (change its size at runtime) easily with just one method call like this :
ArrayList<String> names = new ArrayList<>(Arrays.asList("jey", "abby", "alyssa", "cole", "yzabel", "miho"));
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.size()); i++) {
int randInt = rand.nextInt(names.size());
names.remove(randInt);
}
you can read more about ArrayLists how to add/remove items through this link as well as many tutorials out there just write ArrayList java in google search engine
N.B : I've added Math.min(2, names.length) to the for loop condition as I was afraid you would get to the case that the array length would be less than the number of items you want to delete, using Math.min I'm ensuring that the for loop won't try access an item that isn't there in the array
If you are required to use Arrays then this way is probably among the best
with the limitations involved.
generate a random number and get the name
create a new temporary array to hold the all names less the one removed.
copy all names up to but excluding the one removed to the temp array
copy all names just after the one excluded to the temp array.
assign the temp array to the original array
normal exceptions will be thrown if a null or empty array is used.
Random r = new Random();
String[] names =
{ "jey", "abby", "alyssa", "cole", "yzabel", "miho" };
ArrayList<Integer> a;
int idx = r.nextInt(names.length);
String name = names[idx];
String[] temp = new String[names.length - 1];
for (int i = 0; i < idx; i++) {
temp[i] = names[i];
}
for (int i = idx; i < temp.length; i++) {
temp[i] = names[i + 1];
}
names = temp;
System.out.printf("'%s' was removed.%n",name);
System.out.println(Arrays.toString(names));
Prints something like
'jey' has been removed.
[abby, alyssa, cole, yzabel, miho]
It's interesting to note that the best way would be to use an ArrayList as already given in a previous answer. But the primary reason is that an ArrayList does not need to make a temporary array but simply copies in place. Then it adjusts the size value, effectively hiding the garbage still in the internal array.

I am trying to simply print out a 2D array. But I am getting an error

Eclipse is telling me that, "The type of the expression must be an array type but it resolved to Theater"(The class for the object I created for my 2D array) on the last line of code I have below. Specifically here --> a[row]
This is just one small piece of a larger project I am working on in my Java class. You all may be familiar with it, I have to print and implement a theater seating chart using a 2D array. I have to write methods for searching by price, searching by seat, etc. Right now I am just trying to initialize the 2D array, put some values in it then print them out. Any help is much appreciated.
public class Theater {
//int[][] x = new int[9][10];
int y[][];
public Theater(){
//Initialize array
for (int row = 0; row < 3; row++)
for (int column = 0; column < 10; column++)
y[row][column] = 10;
}
public static void main(String[] args){
Theater a = new Theater();
for(int i = 0; i < 3; i++)
for (int row = 0; row < 9; row++)
for (int column = 0; column < 10; column++)
System.out.println(a[row][column]);
The [] operator needs to be applied to a expression that is an array. Since Theater is not an array, you get a compile time error. You probably wanted to access the y field of the Theater instance:
...
System.out.println(a.y[row][column]);
Furthermore you need to create the y array before using it:
public Theater(){
this.y = new int[9][10];
...
Otherwise this will result in a NullPointerException when trying to write to write to the array (y[row][column] = 10;).

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

Create 2D array of Lists in Java

I'm trying to create a 2D array of lists for a Sudoku. Essentially 81 lists each containing possible solutions to that box in the Sudoku grid. I've tried multiple declarations so far, but whenever I try to add values to a list it returns a null pointer exception. Here is an example, simply populating each of the lists with the numbers 1-9.
List<Integer>[][] sudoku = (List<Integer>[][]) new List[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
for (int k = 1; k < 10; ) {
sudoku[i][j].add(k);
}
}
}
I'm not even positive a 2D array of lists is the optimal way to go about this, but I've done everything from scratch (with a relatively low knowledge of java) so far so I'd like to follow through with this method. The original code looked as follows:
List[][] sudoku = new List[9][9];
Research quickly revealed that this wouldn't cut it.
Thank you in advanced for any help!
Try this one. The general idea, create a master list and while you loop through it, create one inner list.
/* Declare your intended size. */
int mainGridSize = 81;
int innerGridSize = 9;
/* Your master grid. */
List<List<Integer>> mainList = new ArrayList<List<Integer>>(mainGridSize);
/* Your inner grid */
List<Integer> innerList = null;
/* Loop around the mastergrid */
for (int i=0; i<mainGridSize; i++) {
/* create one inner grid for each iteration of the main grid */
innerList = new ArrayList<Integer>(innerGridSize);
/* populate your inner grid */
for (int j=0; j<innerGridSize; j++)
innerList.add(j);
/* add it to your main list */
mainList.add(innerList);
}
Illustrated:
If you need to vary your grid, just change the values of the gridSize.
You cannot create array of generic lists.
You can create List of Lists:
List<List<List<Integer>>> soduko = new ArrayList<>();
And then populate it as you wish.
or use casting:
List[][] soduko = (List<IntegerNode>[][]) new LinkedList[9][9];
You have create the array of Lists but you did not initialize it. Insert this in the second line an the problem should be solved.
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++){
sudoku[i][j]=new ArrayList<Integer>();
}
}
Or to do it all in one go do it like this:
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sudoku[i][j]= new ArrayList<Integer>();
for (int k = 1; k < 10; ) {
sudoku[i][j].add(k);
}
}
}
If you know that you need exactly 81 2D arrays, you can create 3D array:
int[][][] sudoku = new int[81][9][9];
The way you did it now would produce compilation error.

arraylist of a three-dimensional integer vector

I have this three-dimensional array named bands. I need to do 4 copies of it, so I can work in parallel with all of them.
int bands[][][] = new int[param][][];
I need the array to keep being a three dimensional array, as it is the input for some methods that needs an int [][][]
How could I do such copies? I was thinking about using an arrayList like this:
List<Integer[][][]> bandsList = new ArrayList<Integer[][][]>();
bandsList.add(bands);
but I get this error on the last line: The method add(Integer[][][]) in the type List<Integer[][][]> is not applicable for the arguments (int[][][])
so what should I do??
The errors is because int[][][] is not the same as Integer[][][].
int[][][] is an 3D array of primitive int.
Integer[][][] is an 3D array of object Integer, which is the wrapper class of int.
Well, technically a 3D array is an array of pointers to a 2D array, which is an array of pointers to a 1D array which is an array of primitives or pointers to objects.
Use List<int[][][]> bandsList = new ArrayList<int[][][]>(); instead.
Also note that
bandsList.add(bands);
bandsList.add(bands);
will simply add 2 pointers to the same array, changing one will also change the other.
You'll need to manually copy them:
int[][][] getCopy(int[][][] bands)
{
int[][][] newBands = new int[bands.length][][];
for (int i = 0; i < bands.length; i++)
{
newBands[i] = new int[bands[i].length];
for (int j = 0; j < bands[i].length; j++)
{
newBands[i][j] = new int[bands[i][j].length];
System.arraycopy(bands, 0, newBands, 0, bands[i][j].length))
}
}
return newBands;
}
// to add
bandsList.add(getCopy(bands));
in this way you aren't doing a copy of the array, you have to do this 4 times:
int cloneList[][][] = new int[param][..][..];
for(int i = 0; i<bands.length; i++) {
int arr1[][] = bands[i];
for(int j = 0; j<arr1.length; j++) {
int arr2[] = arr1[j];
for(int k = 0; k<arr2.length; k++) {
int x = arr2[k];
cloneList[i][j][k] = x;
}
}
}

Categories