Populate bidimensional array with single array in java - java

how do I populate a matrix in java with a array without using libs?
I have this method
public static String[][] transformArray(String msg, int slice) {
String matrix[][] = new String[slice][msg.length() / slice];
String[] msgArray= mensagem.split("");
for (int j = 0; j < matrix.length; j++) {
for (int h = 0; h < matrix[j].length; h++) {
for (int i = 0; i < matrix.length(); i++ ) {
matrix[j][h] = msgArray[i];
}
}
}
return matrix;
}
And when I call:
String anotherMatrix = transformArray("Java is cool", 2);
My return is this (i have a method to print a matrix):
l l l l l l
l l l l l l
What I'm doing wrong?

I assume you want this
int i = 0;
for (int j = 0; j < matrix.length; j++) {
for (int h = 0; h < matrix[j].length; h++) {
matrix[j][h] = msgArray[i++];
}
}
You should not use 3 loops. What is happening with your code is that for each j and h, the matrix entry is being replaced with every character in turn, so every entry is ending up with the l from cool. There should not be a loop for each entry as you only want one character.

In order to access every element within your 2D-array you would have to iterate like so:
for(int i=0 ; i<n ; i++) {
for(int j=0; j<n ; j++) {
myArray[i][j] = inc;
inc++;
}
}
You instead are using three for-loops which is incorrect. Try adjusting your code to follow this set up, it's really easy. Edit: pbabcdefp has already done that for you!

Related

Cloning two-dimensional Arrays in Java [duplicate]

This question already has answers here:
copy a 2d array in java
(5 answers)
Closed 4 years ago.
I know that similar questions have been asked, but after reading their answers, I keep being unable to solbe my problem: I need to implement the Java method clone, which copies all the double entries in a given two-dimensional array a to a newly created two-dimensional array of the same type and size. This method takes the array a as input and returns the new array with the copied values.
IMPORTANT: I am not not allowed to use a library method to clone the array.
Here's what I've done so far: Maybe I didn't understand the requirements but it didn't work:
class Solution {
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][a.length];
for (int i = 0; i < a.length; i++) {
b[i][i] = a[i][i];
}
return b;
}
}
This is the error message I get:
Status: Done
cloneLonger(weblab.UTest) failed: 'java.lang.AssertionError: expected:<3> but was:<2>'
Test score: 2/3
Something like this should work (with library method):
public class Util{
// clone two dimensional array
public static boolean[][] twoDimensionalArrayClone(boolean[][] a) {
boolean[][] b = new boolean[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
return b;
}
}
In this, your code has few mistakes. These corrections were done below. The two-dimension array has 2 lengths. In this case, you didn't consider inside array length.
class Solution {
static double[][] clone(double[][] a) {
double[][] b = new double[a[0].length][a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
}
you should iterate this array with two loops. This will helps you:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i]= new double[a[i].length];
for (int j = 0; j < a[i].length; j++)
b[i][j] = a[i][j];
}
return b;
}
You have some logical mistakes:
1. Matrix could be sized M x N where M is the number of rows and N is the number of columns. In your solution you are taking for granted that M is always equal to N.
2. You are iterating trough all the rows and there you do set only one column per row like target[K][K] = source[K][K] -> this will go copy the diagonal only and not the whole matrix.
Copy to a temp single row array and then assign it to the out array
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
double[] temp = new double[a[i].length];
for (int j = 0; j < temp.length; j++) {
temp[j] = a[i][j];
}
b[i] = temp;
}
return b;
}
Ever more "advanced" alternatives are:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = new double[a[i].length];
//for (int j = 0; j < a[i].length; ++j) {
// b[i][j] = a[i][
//}
System.arraycopy(a[i], 0, b[i], a[i].length);
}
return b;
}
Now there is a utility class Arrays worth knowing:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = Arrays.copyOf(a[i], 0, [a[i].length]);
}
return b;
}
And for primitive arrays the clone method still may be used. Cloning is not very pure, bypassing constructors, and might be dropped from java in some future.
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
return b;
}
You can't create new array like that. If you are sure that length and width of array is same than only this will work.
class Solution {
static double[][] clone(double[][] a) {
boolean[][] b = new boolean[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = new double[a[i].length];
for (int j = 0; i < a[i].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
}

(Java) The type of the expression must be an array type but it resolved to Object error

The following code:
// Adds game button container
Object[][] gameButtons = new Object[3][3];
// Adds game buttons to game button container
Arrays.fill(gameButtons, new JButton[3][3]);
for (int i = 0; i < gameButtons.length; i++) {
for (int j = 0; j < gameButtons[i].length; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
gameButtons[i][j][k][l] = new JButton();******
}
}
}
}
is throwing me an error:
The type of the expression must be an array type but it resolved to Object. How do I initialize the JButtons?
EDIT: I forgot to clarify. The error was thrown at the line ******
Note that the ****** was not in my code.
EDIT 2: I tried Logan's fix, but it still didn't work:
for (Object[] row : gameButtons)
Arrays.fill(row, new JButton[3][3]);
for (int i = 0; i < gameButtons.length; i++) {
for (int j = 0; j < gameButtons[i].length; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
gameButtons[i][j][k][l] = new JButton();
}
}
}
}
Same error, same place.
gameButtons[i][j] is of type Object, which cannot be indexed as an array. You must first cast it to a JButton[][] type:
for (int i = 0; i < gameButtons.length; i++) {
for (int j = 0; j < gameButtons[i].length; j++) {
// cast it to an array type before accessing
JButton[][] subArray = (JButton[][])(gameButtons[i][j]);
for (int k = 0; k < 3; k++)
for (int l = 0; l < 3; l++)
subArray[k][l] = new JButton();
}
}
I believe you don't need a for loop. If I understand your problem correctly, you can do like this:
//create a sub array
Object[][] subArray = new Object[3][3];
// create game button container
Object[][] gameButtons = new Object[3][3];
// Adds buttons to sub array
Arrays.fill(subArray, new JButton[3][3]);
// Adds sub array to game button container
Arrays.fill(gameButtons, subArray);
The docs helped me a lot with this.
You could also use a GUI maker such as the one in NetBeans IDE it's much simpler than writing the code yourself.

Take two nested for loops. How can I make a variable count further up, after jumping cycling the loops?

I'm sure the answer is fairly simple, but I'm not getting it. Here we go with my example:
int matrix [][] = new int [rows][columns];
for (int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[0].length; j++)
{
mata[i][j] = Integer.parseInt (args[j]);
}
}
How can I make j count further upwards after the programm goes from the inner loop to the outer loop and back to the inner one? Usually, it would start from zero again, which is not intended, as I need the next command line argument. I tried a few things, can't get it to work, though.
You can add an outer variable:
int k = 0;
then replace the innermost line by:
mata[i][j] = Integer.parseInt(args[k]);
k += 1;
Or compute it:
mata[i][j] = Integer.parseInt(args[i * matrix.length + j]);
Just use a separate variable (argc below):
int matrix[][] = new int[rows][columns];
for (int i = 0, argc = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++, argc++) {
mata[i][j] = Integer.parseInt(args[argc]);
}
}

Java: Storing values in 2D Array

I have a problem with storing values in a multidimensional array. The main concept of the idea is that I have an arraylist which is called user_decide and I transform it in a array. So, the decide array looks like [1, 45, 656, 8, 97, 897], but all the rows don't have the same number of elements. Then, I split this replace [,] and spaces and I would like to store each value individually in a 2D array. So, I split it with the "," and try to store each value in a different position. Everything seems to be printed great, even the cut[j] is what I want to store, but I get a java.lang.NullPointerException, which I don't get. The count variable is actually the count = user_decide.size()
String [] decide = user_decide.toArray(new String[user_decide.size()]);
for (int i = 0; i < count; i ++){
decide[i] =
decide[i].replaceAll("\\s", "").replaceAll("\\[","").replaceAll("\\]", "");
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Another question is why I cannot store it in a Int [][] array? Is there a way to do that?
Thank you a lot.
** EDIT **
I just made an edit about my answer after I accepted the question. I am trying to store it in a 2D int array.
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length];
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
Ivaylo Strandjev's answer shows the reason for your problem. But there's a much simpler solution:
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
data1[i] = decide[i].split("\\,");
System.out.println(Arrays.toString(data1[i]));
}
Also, you don't need to escape the comma.
EDIT
Saw your edit. There is a big mistake, see my comment in your code:
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length]; // This line has to be prior to the
// inner loop, or else you'll overwrite everything but the last number.
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
If all you want is the int[], this is what I would do:
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
String[] temp = decide[i].split(",");
data[i] = new int [temp.length];
for (int j = 0; j < temp.length; j++){
data[i][j] = Integer.parseInt(temp[j]);
System.out.println(data1[i][j]);
}
}
There are probably nicer ways, but I don't know why you are using user_decide.size() ( a Collection) for the condition and decide[i] (an array) within the loop. There's no good reason I can think of mixing this, as it could lead to errors.
In java you will need to also allocate data[i], before copying contents:
for (int i = 0; i < count; i++){
data1[i] = new String[cut.length];
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Before copying contents:

size of Two-dimensional arrays in Java

I want to make a loop on Two-dimensional array in Java.
How I do that? I wrote:
for (int i = 0; i<=albums.size() - 1; i++){
for (int j = 0; j<=albums.size() - 1; j++){
But it didn't work. Thanks.
Arrays have a read-only field called length, not a method called size. A corrected loop looks like this:
for(int i = 0; i < albums.length; i++ ) {
for (int j = 0; j < albums[i].length; j++) {
element = albums[i][j];
You have to recognize that a 2-D array is just an array whose element type happens to be another array. So the i loop iterates over each element in albums (which is an array) and the j loop iterates over that child array (with a potentially different size).
A more transparent way would be like this:
String[][] albums;
for(int i = 0; i < albums.length; i++ ) {
String[] childArrayAtI = albums[i];
for (int j = 0; j < childArrayAtI.length; j++) {
String element = childArrayAtI[j];
}
}
Try this if you are working with Java 1.5+:
for(int [] album : albums) {
for(int albumNo : album) {
System.out.print(albumNo + ", ");
}
System.out.println();
}
First of all, a two-dimensional array looks like this in Java:
int[][] albums = new int[10][10];
Now, for iterating over it:
for (int i = 0; i < albums.length; i++) {
for (int j = 0; j < albums[i].length; j++) {
int value = albums[i][j];
}
}

Categories

Resources