Adding an array of strings into a 2D array [duplicate] - java

This question already has answers here:
How to add strings from one array into another array in Java
(3 answers)
Closed 8 years ago.
So I need to add an array of strings, into a two dimensional array called squares. The array squares is a 10 by 10 array in which the first row of initStrings will match up with squares.
IE - static String[] strings = {"hello"}
The h would be in the first location of the squares array, the e would be in the second and so on. Im wondering how to do this.
static String[] initStrings =
{
"...../...\\",
"..\\.......",
"......./..",
"..........",
"........\\.",
"..........",
"..........",
".....\\../.",
"..\\....../",
".........."
};
I know that I need to have a nested for loop. Something along the lines of
for (col = 0; col < 10; col++)
{
for (rows = 0; rows < 10; rows ++)
{
// what goes here?
}
}

is this what you want?
char[][] squares=new char[10][10];
String[] initStrings = { "...../....", "../.......", "......./..", "..........", "......../.", "..........", "..........", "...../../.", "../....../", ".........." };
int i=0;
for(char[] squareRow:squares)
squareRow=initStrings[i++].toCharArray();

This might help:
static String[] initStrings = { "...../...\", "..\.......", "......./..", "..........", "........\.", "..........", "..........", ".....\../.", "..\....../", ".........." };
char[][] squares = new char[10][10];
int row, col;
for (row = 0; row < 10; rows ++)
{
for (col = 0; col < 10; col++)
{
squares[row][col] = initStrings[row].charAt(col);
}
}
// print squares
for (row = 0; row < 10; rows ++)
{
for (col = 0; col < 10; col++)
{
System.out.print(squares[row][col] + " ");
}
System.out.print("\n");
}

Here's another possible solution. It's a bit overkill, but I like maps, and lists :) One advantage with this is that if you add a new string to your initStrings with more than 10 chars, it should still finish. But, maybe that would be bad...
String[] initStrings = {"...../...\\", "..\\.......", "......./..", "..........", "........\\.", "..........", "..........", ".....\\../.", "..\\....../", ".........." };
Map<Integer, List<String>> columnEntries = new TreeMap<Integer, List<String>>();
for(String str : initStrings) {
for(int i = 0; i < str.length(); i++) {
if(!columnEntries.containsKey(i)) {
columnEntries.put(i, new ArrayList<String>());
}
columnEntries.get(i).add(str.substring(i,i+1));
}
}
//Print results...
for(Entry<Integer, List<String>> e : columnEntries.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}

Related

1-Dimensional array -> 2D array

So i'm a beginner;
The task is to convert a given string into the array, the string always has the first characcter as the amount of rows and the second character as the amount of columns.
My problem is to solve how to move the rest of the string 's' into the 2D array from the 1D array.
Thanks in advance!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split(" ");
int arows = Integer.parseInt(s[0]);
int acols = Integer.parseInt(s[1]);
int[][] cells = new int[arows][acols];
for (int col = 0; col < acols; col++){
for (int row = 0; row <= arows;row++){
cells[row][col] = Integer.parseInt(s[2]);
}
}
}
}
You need to implement a counter for your for-loops to iterate through the input string. What you are doing right now is to fill your 2D-Array with the third element of your string.
One solution would be to just declare a variable i = 2, and increment it for each pass of the inner for-loop.
int i = 2
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
Edit: removed <= in row loop, changed the initial value of the index to 2
This is the solution, you have to put another iterator, and initialize it to 2, so to skip the first two elements of s[]
int i = 2;
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}

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?)

Storing twodimensional array into single dimensional array

Please help me to fix this. I just want to store a two dimensional array into a single dimensional array is it possible. what I'm trying is that I have to store two dimensional integer array which will be created dynamically.
Try like this:
int[][] arr = new int[Rows][Cols];
int[] arr1D= new int[Rows * Cols];
Rows = arr.length;
if (Rows > 0) {
Cols = arr[0].length;
} else {
Cols = 0;
}
for (int row = 0, count = 0; row < Rows; row++) {
for (int col = 0; col < Cols; col++) {
arr1D[count] = arr[row][col];
count++;
}
}
One way of doing it
import java.util.ArrayList;
public class Test1 {
public static void main(String[] args) {
int[][] twoDArrays={{10,5},{4,6},{9,8}};
ArrayList<Integer> oneDArray= new ArrayList<Integer>();
for(int i=0; i<twoDArrays.length;i++){
for(int j=0;j<twoDArrays[i].length;j++){
oneDArray.add(twoDArrays[i][j]);
}
}//printing onedArray
for(Integer s:oneDArray){
System.out.println(s);
}
}
}
Output:
10
5
4
6
9
8

Convert a 1D string to a 2D array of Integers

I have a string and I want to convert it to a 2D array of integers. This is what I am doing:
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
//Putting each element into an array of strings
String stringArray[]=string1.split("~");
//Determining the number of columns for the 2D array
int countints=0;
Scanner ins = new Scanner(stringArray[0]);
while (ins.hasNext()){
countints+=1;
ins.next();
}
//converting into an array of integers
int intArray[][]=new int[stringArray.length][countints];
Here I'm stuck as how to parse each integer into the 2D array.
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String string2 = string1.replace("[","").replace("]","");
for(int i = 0; i < stringArray.length; i++)
{
String s = stringArray[i].substring(1, stringArray[i].length()-1);
String[] elementArray = s.split(",");
for(int j = 0; j < elementArray.length; j++)
{
int val = Integer.parseInt(elementArray[j]);
intArray[i][j] = val;
}
}
For a totally dynamic array:
String string1 = "[1,2,3]~[4,5,6]~[7,8,9]~";
String[] lines = string1.split("(^|~)\\[");
int[][] array = new int[lines.length][0];
Pattern pat = Pattern.compile("\\d+");
int lineIndex = 0;
for (String line : lines) {
//if the row size is dynamic
Matcher m1 = pat.matcher(line);
int rowSize = 0;
while (m1.find())
rowSize++;
array[lineIndex] = new int[rowSize];
int colIndex = 0;
Matcher m2 = pat.matcher(line);
while (m2.find()) {
array[lineIndex][colIndex++] = Integer.parseInt(m2.group());
}
lineIndex++;
}
for(int i=0; i<array.length;i++){
for(int j=0; j<array[i].length;j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
It prints:
1 2 3
4 5 6
7 8 9
Once you have initialized the 2D array, you need to parse each element in stringArray by getting rid of trailing and leading '[', ']' bracket pairs and splitting it with "," and parse each element of the split string into Integer and put that int value to the given 2d array at correct postion.
EDIT: WORKING SOLUTION
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String stringArray[]=string1.split("~");
int countints = stringArray[0].substring(1, stringArray[0].length()-1).split(",").length;
int intArray[][]=new int[stringArray.length][countints];
for(int i = 0; i < stringArray.length; i++)
{
String s = stringArray[i].substring(1, stringArray[i].length()-1);
String[] elementArray = s.split(",");
for(int j = 0; j < elementArray.length; j++)
{
int val = Integer.parseInt(elementArray[j]);
intArray[i][j] = val;
}
}
Here is a clean solution that works. I started working on it before I got through all of the other answers, so my apologies if it doesn't meaningfully add to what is already here:
public class SO {
public static int[][] parse(String input) {
String[] rows = input.split("~");
int[][] ints = new int[rows.length][];
int j = 0;
for(String row : rows) {
String[] cols = row.substring(1, row.length()-1).split(",");
int k = 0;
ints[j] = new int[cols.length];
for(String col : cols) {
ints[j][k++] = Integer.parseInt(col);
}
j++;
}
return ints;
}
public static void main(String[] args) {
for(int[] row : parse("[1,2,3]~[4,5,6]~[7,8,9]~")) {
for(int col : row) {
System.out.print(","+col);
}
System.out.println();
}
}
}
This produces the output:
,1,2,3
,4,5,6
,7,8,9
As for error checking you should decide upfront how you want to handle error checking, As this is written a single invalid int will throw an exception, which I think is the correct behavior. Malformed rows on the other hand might give unpredictable output (which I would say is wrong if the input has even the slightest potential to be malformed).

Categories