Select element j in each column of an array in JAVA - java

I have the array
String[] test_=new String[] {"a b c d", "f g h i","j k l s gf"};
Now i want to create another array that has the elements
{"b d", "g i","k s"}
how can I do this?
I've managed to separate the array into rows using
String split_test[] = null;
for (int j = 0 ; j <= 2 ; j++) {
split_test=test_[j].split("\\s+");
System.out.println(Arrays.toString(split_test));
}
But now I want to separate each of those rows, I tried the solution of
How to Fill a 2d array with a 1d array? Combined with something like this split_test=test_[j].split("\s+"), but I haven't been able to solve it.
Also If I do what they say I have to make the array split_test have a number of specific columns, but what I want is the size of the columns of split_test depend of the array test_. For example in case I want to have an array with the elements {"b d", "g i", "k s gf"}
String[][] split_test = new String[3][2];
for(int row = 0; row < split_test.length; row++) {
for(int col = 0; col < split_test[row].length; col++) {
split_test[row][col] = test_[row];/*I still don't understand how to use the split within the for*/
System.out.println(split_test[row][col]);
}
}
Is there a simpler and more efficient way of doing this?
Thanks

Here is another one.
You can use the substring method of String class.
Or use indexes of the array returned by the split method.
String output[] = new String[test_.length];
String split_test[] = null;
for (int j = 0; j < test_.length(); j++) {
split_test = test_[j].split("\\s+");
// use direct index
// output2[j] = split_test[1] + " " + split_test[3];
// or based on length
output[j] = split_test[1] + " " + split_test[split_test.length - 2];
}
System.out.println(Arrays.toString(output));
Output:
b d
g i
k s

I have used a different approach that works as well. I noticed you only take the uneven indexes, hence my modulo approach:
String[] array = new String[] {"a b c d", "f g h i","j k l s gf"};
String[] result = new String[array.length];
for(int i = 0; i < array.length; i++) {
String subresult = "";
String[] array2 = array[i].split(" ");
for(int j = 0; j < array2.length; j++) {
if(j % 2 == 1)
subresult += array2[j] +" ";
}
result[i] = subresult.trim();
}

You should use a 2 dimentional array, you can create one by doing:
String[][] input=new String[][] {{"a","b","c","d"}, {"f","g","h","i"},{"j","k","l","s"}};
You can then do something like this to retrieve {{"b","d"}, {"g","i"},{"k","s"}}:
String[][] output = new String[input.length][2];
for(int i = 0; i<input.length; i++)
{
output[i] = new String[]{input[i][1],input[i][3]};
}
System.out.println(Arrays.deepToString(output));

Related

Displaying the string values of 2 dimensional Object array

I am trying to display the contents of an array after iterating through rows and columns of a JTable. I tried Arrays.toString(myTwoDimensionalArrayVariable) but it won't display the string values.
My goal is to check duplicates for every column per row of a destination JTable when user tries to add row values from a source JTable that's why I want to display the contents of the array.
The values on columns are combination of double, String, and int.
int myRowCount = aJTableParameter.getRowCount();
int myColumnCount = aJTableParameter.getColumnCount();
Object[][] myRowValues = new Object[myRowCount][myColumnCount];
for (int j = 0; j < myRowCount; j++) {
for(int i = 0; i< myColumnCount; i++){
myRowValues[j][i] = aDestinationTable.getValueAt(j, i);
}
}
System.out.println(Arrays.toString(myRowValues));
if (Arrays.asList(myRowValues).contains(column1Value)
&& Arrays.asList(myRowValues).contains(column2Value)
&& Arrays.asList(myRowValues).contains(column3Value)
&& Arrays.asList(myRowValues).contains(column4Value)) {
JOptionPane.showMessageDialog(null, "Duplicate, try again.");
}else{
//do something else
}
I only get this output:
run:
Successfully recorded login timestamp
[]
[[Ljava.lang.Object;#35fa3ff2]
[[Ljava.lang.Object;#407c448d, [Ljava.lang.Object;#1e78a60e]
Is there any other alternative than using 2 Dimensional Arrays?
I'd appreciate any help.
Thanks.
IFF your JTable cells contain only Strings, you can define your array as String[][] instead of Object[][] and fill it with your JTable contents using aDestinationTable.getValueAt(j, i).toString().
EDIT: since that's not the case (as per your comment), it's probably better to use a List, like this:
List<List<Object>> objectList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
objectList.add(j, new ArrayList<>());
for (int i = 0; i < 2; i++) {
if (i==0) objectList.get(j).add("string" + j + i);
if (i==1) objectList.get(j).add((double) 37.8346 * j * i);
}
}
System.out.println("OBJECT LIST: "+objectList);
Output:
OBJECT LIST: [[string00, 0.0], [string10, 37.8346]]
Your code should look like this, then:
List<List<Object>> myRowValues = new ArrayList<>();
for (int j = 0; j < myRowCount; j++) {
myRowValues.add(j, new ArrayList<>());
for (int i = 0; i < myColumnCount; i++) {
myRowValues.get(j).add(aDestinationTable.getValueAt(j, i));
}
}
System.out.println(myRowValues);

Creating a multi-dimensional String array from a method array parameter

I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)

Combining elements in jagged 2D arrays into one new jagged 2D array (Deep Copy issue)

Given two jagged arrays: a & b where a + b will always have the same # of rows:
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
how exactly can I manipulate a new jagged array c to return:
{ {1,2,7}, {4,5,6,8,9,0} }?
Here's what I have so far:
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
//rest of my code for assigning the values into the appropriate position works.
The trouble arises, as you all can see, that I am performing a deep copy, which, on the second iteration of the for-loop, is setting ALL rows to a length of the length of the current row on the step of the iteration.
Flaw in your approach
You are creating a new 2D array object each iteration of your loop. Each time through, you are reassigning c, thus throwing out all of your previous work. Additionally, placing a number in both set of brackets at the same time results in each row having the same length.
Using your example, the first time through the loop, c is assigned to a 2D array with two rows, each of length three. The second time through the loop, you throw out your previous 2D array and create a new one having two rows, each of length six.
But what you need to be doing is creating a new row each time through the loop, not the entire 2D array.
Solution
First, we create a 2D array called c and specify that it has a.length rows. We don't put a value in the second bracket, because that would indicate that all of the rows are of the same length. So at this point, c does not know about row length. It just knows how many rows it can have. Keep in mind: c doesn't actually have any rows yet, just a capacity for a.length rows.
Next, we must create the rows and assign a length/capacity to them. We set up our loop to run as many times as there are rows. The current row index is denoted by i, and therefore, c[i] refers to a specific row in the 2D c array. We use new int[] to create each individual row/array, but inside the brackets, we must specify the length of the current row. For any row c[i], its length is given by the sum of the lengths of a[i] and b[i]; that is, a[i].length + b[i].length.
What we are left with is an array c that contains rows/arrays, each with a set length/capacity that matches the sum of the corresponding rows lengths in a and b.
Keep in mind that c still does not contain any integer values, only containers that are of the correct size to hold the values in a and b. As you mentioned, you already have code to populate your array with values.
int[][] c = new int[a.length][];
for (int i = 0; i < a.length; i++) {
c[i] = new int[a[i].length + b[i].length];
}
When initialize Java 2D array, lets consider it as a table; you only have to give the number of rows and in each row of your table can have different number of columns.
Eg. Say we have a 2D array call c defined as follows,
int[][] c = new int[10][];
It says you defined c contains 10 of int[] elements. But in order to use it you have to define the number of columns each row has.
Eg. Say we have 3 columns in the second row
int c[1] = new int[3];
So in this example you have to add the column values of 2D arrays a and b to calculate the resultant array which is c.
c[i] = new int[a[i].length + b[i].length];
This will give you what you expected.
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
int[][] c = new int[a.length][];
for(int i = 0; i<a.length; i++){
c[i] = new int[a[i].length + b[i].length];
for (int j=0;j< a[i].length; j++) {
c[i][j] = a[i][j];
}
int length = a[i].length;
for (int j=0;j< b[i].length; j++) {
c[i][length+j] = b[i][j];
}
}
Try c[i] = new int[a[i].length + b[i].length]
int[][] c = new int[a.length][];
for(int i = 0; i < c.length; i++){
c[i] = new int[a[i].length + b[i].length];
int x = 0;
for (int num : a[i]) {
c[i][x] = num;
x++;
}
for (int num : b[i]) {
c[i][x] = num;
x++;
}
}
or even simpler...
int[][] c = new int[a.length][];
for(int i = 0; i < c.length; i++){
c[i] = new int[a[i].length + b[i].length];
System.arraycopy(a[i], 0, c[i], 0, a[i].length);
System.arraycopy(b[i], 0, c[i], a[i].length, b[i].length);
}
Try this one:
int[][] c = new int[a.length][];
for(int i = 0; i<a.length; i++){
c[i] = new int [a[i].length + b[i].length];
int j;
for(j=0; i < a[i].length; j++){
c[i][j] = a[i][j];
}
for(int k=0; i < b[i].length; k++){
c[i][j+k] = b[i][j];
}
}
public static void main(String [] args) {
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
for(int i = 0; i<a.length; i++){
for (int j = 0; j < a[i].length+b[i].length; j++) {
if(j< a[i].length){
c[i][j]=a[i][j];
}
if(j< a[i].length+b[i].length && j>= a[i].length){
c[i][j]=b[i][j-a[i].length];
}
}
}
for(int i = 0; i<a.length; i++){
for (int j = 0; j < a[i].length+b[i].length; j++) {
System.out.print(c[i][j]);
}
System.out.println();
}
}
This works in my system ...........

Shuffle the order of a 2D array in java

I'm creating my own memory game. Everything is going well so far. Just to let you know I'm using processing for Java. I have created a 2 dim PImage array. This is the code for filling the 2D array:
int g = 0;
for(int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
if (j % 2 == 0) {
kaart[i][j] = loadImage( g + ".jpg" );
kaart[i][j].resize(vlakGrootte - 1, vlakGrootte - 1);
g++;
} else if (j % 2 == 1) {
kaart[i][j] = kaart[i][j-1];
}
}
}
I want the items in this array to be shuffled. It seems like java collections does not support to shuffle a 2D PImage array? Please correct me if im wrong.
Thanks to you all for helping me out.
1).Shuffle per-outter index :
YourType [][] kaart = new YourType [..][..];
List <YourType[]> list = (List<YourType[]> ) Arrays.asList(kaart);
Collections.shuffle(list);
kaart = (YourType[][]) list.toArray(new YourType[0][]);//convert back to a array
// just for checking
for(YourType[] k:kaart ){System.out.println(Arrays.toString(k));}
Replace YourType with the type of kaart.
2). Shuffle per-Outter+Inner index :
YourType[][] kaart = new YourType[..][..];
List<YourType[]> temp = new ArrayList<>();
for(YourType[] k:kaart ){
List <YourType> list = (List<YourType> ) Arrays.asList(k);
Collections.shuffle(list);//shuffle
YourType[] tempArray = (YourType[]) list.toArray();
temp.add(tempArray);
}
Collections.shuffle(temp);
kaart= (YourType[][]) temp.toArray(new YourType[0][]);//convert back to a array
// just for checking
for(YourType[] k:kaart ){System.out.println(Arrays.toString(k)); }
Replace YourType with the type of kaart.
3). Shuffle in The easiest way:
Just put all elements into a single List then call Collections.shuffle()
I would do this the same way you would deal those cards in real world. First you shuffle the deck:
ArrayList<Integer> pieces = new ArrayList<Integer>();
for (int i = 0; i < 4 * 6 / 2; i++) {
for (int j = 0; j < 2; j++) {
pieces.add(i);
}
}
Collections.shuffle(pieces);
Then you deal cards out of shuffled deck:
for(int i = 0; i < 4; i++) {
for (int j = 0; j < 6; j++) {
int g = pieces.remove(pieces.size()-1);
kaart[i][j] = loadImage( g + ".jpg" );
kaart[i][j].resize(vlakGrootte - 1, vlakGrootte - 1);
}
}

Put two arrays to Jtable rows

I have two arrays, which is equal in terms of number of elements. I want to put it in a JTable rows (like in the ascii table example from bellow). I'm using table model and a loop for both arrays, but I archive something else (see print screen).
Note: I want to maintain the correspondence between elements of both arrays, like in the ascii table example.
Integer[] intArray = new Integer[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
intArray[i] = Integer.parseInt(stringArray[i]);
}
System.out.println(Arrays.toString(intArray)); //output [285, 715, 1437, 1749]
Integer[] intArray1 = new Integer[stringArray1.length];
for (int i = 0; i < stringArray1.length; i++) {
intArray1[i] = Integer.parseInt(stringArray1[i]);
}
System.out.println(Arrays.toString(intArray1)); //output [0, 0, 1087, 0]
DefaultTableModel modelPeaks = new DefaultTableModel();
JTable table = new JTable(modelPeaks);
modelPeaks.addColumn("1st Column");
modelPeaks.addColumn("2nd Column");
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray1.length; j++) {
modelPeaks.addRow(new Object[]{intArray[i], intArray1[j]});
}
}
The output is:
But I want to archive this:
+--------------------+--------------------+
+ 1st Column + 2nd Column +
+--------------------+--------------------+
+ 285 + 0 +
+ 715 + 0 +
+ 1437 + 1087 +
+ 1749 + 0 +
+--------------------+--------------------+
I think that is from the loop, but I can't figure out how to fix it. Someone can help me? And thanks in advance for your time.
The last loop should read
for (int i = 0; i < intArray.length; i++) {
modelPeaks.addRow(new Object[]{intArray[i], intArray1[i]});
}
Always make sure that both array have the same length.
If the arrays are both the same length you can use the same iterator for both:
for (int i = 0; i < intArray.length; i++) {
modelPeaks.addRow(new Object[]{intArray[i], intArray1[i]});
}

Categories