For example I have some comma separated strings
"aron, IA52, 20"
"john, IA61, 23"
"kleo, IA32, 42"
How can I convert them to a 2 dimensional array in the easiest way possible?
As already pointed out in comments, you should use split() while iterating over your comma separated string list and populate your array accordingly. Here is sample code to give you some idea:
List<String> input = Arrays.asList("aron, IA52, 20", "john, IA61, 23", "kleo, IA32, 42");
String[][] array = new String[3][3];
int row = 0;
// Loop Over Comma Separated List and split each string to populate 2D array
for (String commaSeparatedStr : input) {
String[] parts = commaSeparatedStr.split(",");
System.arraycopy(parts, 0, array[row], 0, parts.length);
row++;
}
// Print array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(array[i][j]);
System.out.println();
}
This prints:
aron IA52 20
john IA61 23
kleo IA32 42
The provided function will parse the string to the 2D matrix.
Below is the format of the string that you need to provide to this function.
1.2,2.3,3.5\n3.1,4.70,5.0
function
public double[][] parseStingToArray(String str) {
System.out.println(str);
String arr1[] = str.split("\n");
double[][] ans = new double[arr1.length][];
for (int i = 0; i < arr1.length; i++) {
String[] col = arr1[i].split(",");
ans[i] = new double[col.length];
for (int j = 0; j < col.length; j++) {
ans[i][j] = Double.parseDouble(col[j]);
}
}
doubleArray = ans;
return ans;
}
Related
i have a a string array which contains two integer array ["[1,2,3]","[4,5,6,7,8]"]
I want to add the elements of integer array for example - 1+4,2+5,3+6 and store and print the result in a single integer array - [4,7,9,7,8]
What is the efficient approach to solving this problem?
Try this:
String[] strArray={"[1,2,3]","[4,5,6,7,8]"};
String[] strArray1 = strArray[0].substring(1, strArray[0].length()-1).split(",");
String[] strArray2 = strArray[1].substring(1, strArray[1].length()-1).split(",");
int maxArrLength = Math.max(strArray1.length, strArray2.length);
int[] resultIntArray = new int[maxArrLength];
for (int i=0; i < maxArrLength; i++) {
if (strArray1.length>i) resultIntArray[i] += Integer.valueOf(strArray1[i]);
if (strArray2.length>i) resultIntArray[i] += Integer.valueOf(strArray2[i]);
}
System.out.println(Arrays.toString(resultIntArray));
String[] strArray={"[1,2,3]","[4,5,6,7,8]"};
String[] s1=strArray[0].substring(1, strArray[0].length() - 1).split(",");
String[] s2=strArray[1].substring(1, strArray[1].length() - 1).split(",");
// put string array length which ever length is bigger like in this case s2 is bigger than s1 and loop through it.
Integer[] output = new Integer[s2.length];
for(int i=0; i < s2.length; i++) {
if(i < s1.length) {
output[i] = Integer.parseInt(s1[i]) + Integer.parseInt(s2[i]);
} else {
output[i] = Integer.parseInt(s2[i]);
}
}
for(int j=0;j<output.length;j++) {
System.out.println(output[j]);
}
I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.
I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2
I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}
I have a String:
1,3,4,5,
1,4,5,0,
2,5,3,8,
That I want to store in a variable matrix (int[][]). What is the best way to accomplish this? Should I use the String class' methods? Or should I use a Regex?
First (by String.split(..)) split on newline, then split the items of each of the resultant array on ,. Then parse each using Integer.parseInt(..)
String input = "1,3,4,5,\n1,4,5,0,\n2,5,3,8,";
String[] str1 = input.split("\n");
int[][] matrix = new int[str1.length][];
for (int i = 0; i < matrix.length; i++) {
String[] str2 = str1[i].split(",");
matrix[i] = new int[str2.length];
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = Integer.parseInt(str2[j]);
}
}