How to insert an array into a two dimensional array - java

I have created an array under
public class program {
public static String[] tasks = new String[5];
}
Now I want to create a two dimensional String array with that existing String array (tasks) and a new String array (date) in order to have synchronized data.
How would one go about that in Java?

Can you explain more on the problem. This can be simply achieved using pojo. I couldn't comment so added it as ans.
You can covert array to list. Can this example is helpful. What is the use of Collections.synchronizedList() method? It doesn't seem to synchronize the list
OR
public String[][] arr = new String[5][2]; // not sure why you need static
for (int i = 0; i < 5; i++) { // you can take constant or array length
arr[i][0] = new Date().toString(); // or System milliseconds as string
arr[i][1] = tasks[0];
}

Like so
public static String[][] tasksWithDate = new String[task.length][2];
You can push your old data with a simple loop
for (int i = 0; i < task.length; i++) {
taskWithDate[i][0] = tasks[0];
}
If you access the new array you can access a specfific task via taskWithDate[i][0] and the date with taskWithDate[i][1]

First, a 2D array is an array of arrays.
So to create a two dimensional array, you do it like so:
String[][] tasks = new String[5][2];
This creates a 2D array with 5 rows and 2 columns.
To insert a record into the first row and first column, you do it like so:
tasks[0][0] = "My new string";
To loop through a 2D array, you will need 2 loops.
for (int row = 0; row < tasks.length; row++) {
for (int col = 0; col < tasks[row].length; col++) {
tasks[row][col] = "New string for index row " + row + " col " + col;
}
}

Below example will give you complete context.
Adding Tasks with some values
Creating Two Dimension array, where first index will present tasks value and 2nd index is Date.
Printing all values.
public static void method() {
String[] tasks = { "1", "2", "3", "4", "5" };//new String[5];
String[][] taskTwoDim = new String[tasks.length][2];
//Adding values to two dimension array, 0->tasks, 1->String Date
for (int i = 0; i < tasks.length; i++) {
taskTwoDim[i][0] = tasks[i];
taskTwoDim[i][1] = new Date().toString();
}
//Printing all values which is present on index-0, index-1
for (int a = 0; a < taskTwoDim.length; a++) {
System.out.println(taskTwoDim[a][0] + " " + taskTwoDim[a][1]);
}
}

If I understand your question right, you can create a 2d array from 2 one-dimensional arrays by simply doing this:
int[][] resultArray = {task, date};

If I understand your question correctly, it is better to create a new POJO class TaskDate.
public class program {
public static TaskDate[] tasks = new TaskDate[5];
}
class TaskDate {
private String task;
private String date;
// todo add a constructor, getters, and setters
}

Related

Convert a string into a multidimensional arrays with different lengths

I need to execute by command line a code that will provide a multidimensional array with elements with not necessarily equal lengths.
The execution string is bellow:
start /wait java -jar testMSMWithIndex.jar Foursquare_weather_day_root-type_type 0,1,2-4
I'm considering to pass the parameter 0,1,2-4 and then convert it in a multidimensional array with elements of different lengths in this case, i.e. {{0}, {1}, {2, 4}}.
Note that {{0, null}, {1, null}, {2, 4}} does not work to my problem.
Do you guys know how to develop a method or even get directly as an array from args?
I really appreciate any help you can provide.
It's doubtful that anything already exists to do this for you, so you'll have to parse the string for yourself. Something like this would do it:
public static int[][] parseRaggedArrayFromString(String s)
throws NumberFormatException {
String[] ss = s.split(",");
int[][] result = new int[ss.length][];
for (int i = 0; i < ss.length; ++i) {
if (!ss[i].contains("-")) {
result[i] = new int[1];
result[i][0] = Integer.parseInt(ss[i]);
} else {
String[] range = ss[i].split("-", 2);
int lo = Integer.parseInt(range[0]);
int hi = Integer.parseInt(range[1]);
int size = hi - lo + 1;
result[i] = new int[size > 0 ? size : 1];
int j = 0;
do {
result[i][j] = lo;
++lo;
++j;
} while (lo <= hi);
}
}
return result;
}
It's basically a split on , and -. From there is just handling the data. Comments in the code.
/**
* #author sedj601
*/
public class Main {
public static void main(String[] args) {
String input = "0,1,2-3";
String[] firstArray = input.split(",");//Split on ,.
String[][] outputArray = new String[firstArray.length][];//The array that will be holding the output
//Used to process the firstArray
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i].length() > 1) {//If the lenght is greater than one. split on -.
String[] secondArray = firstArray[i].split("-");
//Subtract the two numbers and add one to get the lenght of the array that will hold these values
int arrayLength = Integer.parseInt(secondArray[1]) - Integer.parseInt(secondArray[0]) + 1;
String[] tempArray = new String[arrayLength];
int increment = 0;//Keeps up with the tempArray index.
//loop from the first number to the last number inclusively.
for (int t = Integer.parseInt(secondArray[0]); t <= Integer.parseInt(secondArray[1]); t++) {
tempArray[increment++] = Integer.toString(t);//Add the data to the array.
}
outputArray[i] = tempArray;//Add the array to the output array.
} else {//If the lenght is 1, creat an array and add the current data.
String[] tempArray = new String[1];
tempArray[0] = firstArray[i];
outputArray[i] = tempArray;
}
}
//Print the output.
for (String[] x : outputArray) {
for (String y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Output:
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
0
1
2 3
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.194 s
Finished at: 2021-01-08T00:08:15-06:00
------------------------------------------------------------------------
I really think that's possible when you create an array of type Object .(not a good idea) Since multi-D arrays can only hold arrays of same length (int[][]). Then you create and retrieve values from array by casting...
I am trying here to be creative and adopt to your requirements..
public class x {
public static void main(String[] args) {
Object[] arguments = new Object[args.length];
// Then make a loop to capture arguments in array..
// or add manually
arguments[0] = new String[]{args[0]};
arguments[1] = new String[]{args[1],args[2]};
//Then retrieve info from object later by casting
System.out.println(java.util.Arrays.toString((String[]) arguments[1]));
}
}
...
Although, please consider using a collection...
While I waited for the answer, I found a way to solve the problem.
The relevant information here is that we do not need to set the second array dimension in its instantiation.
The code is below:
// INPUT string = "2-3,1,4-5"
private static String[][] featuresConversion(String string) {
String[] firstLevel = string.split(","); // 1st lvl separator
String[][] features = new String[firstLevel.length][]; // Sets 1st lvl length only
int i = 0;
for (String element : firstLevel) {
features[i++] = element.split("-");
}
return features;
}
I want to thank you all. All suggested solutions also work fine!

Java-Array Splitting

I have array of string {"All-Inclusive,All Inclusive","Luxury,Luxury","Spa-And-Relaxation,Spa & Relaxation"}
I want to split them based on "," with two arrays, first array {"All-Inclusive","Luxury","Spa-And-Relaxation"} and a second array {"All Inclusive","Luxury","Spa & Relaxation"}.
Can you kindly suggest how can it be done?
You could iterate your array of String(s). For each element, call String.split(String) and that will produce a temporary array. Make sure you got two String(s) from the array and then assign it to your output first and second like
public static void main(String[] args) {
String[] arr = { "All-Inclusive,All Inclusive", "Luxury,Luxury",
"Spa-And-Relaxation,Spa & Relaxation" };
String[] first = new String[arr.length];
String[] second = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
String[] t = arr[i].split("\\s*,\\s*");
if (t.length == 2) {
first[i] = t[0];
second[i] = t[1];
}
}
System.out.printf("First = %s%n", Arrays.toString(first));
System.out.printf("Second = %s%n", Arrays.toString(second));
}
Output is
First = [All-Inclusive, Luxury, Spa-And-Relaxation]
Second = [All Inclusive, Luxury, Spa & Relaxation]

Update 2d String array with method that takes in two 2d string arrays

I have to take in a 2d array and multiple each row of it by the other corresponding 2d array.
Here are the files:
Omaha,104,1218,418,216,438,618,274,234,510,538,740,540
Saint Louis,72,1006,392,686,626,670,204,286,236,344,394,930
Des Moines,116,1226,476,330,444,464,366,230,602,260,518,692
Chicago,408,948,80,472,626,290,372,282,488,456,376,580
Kansas City,308,1210,450,234,616,414,500,330,486,214,638,586
Austin,500,812,226,470,388,488,512,254,210,388,738,686
Houston,454,1086,430,616,356,534,218,420,494,382,476,846
New Orleans,304,1278,352,598,288,228,532,418,314,496,616,882
File Two:
Omaha,7.5
Saint Louis,10.5
Des Moines,8.5
Chicago,11.5
Kansas City,12.5
Austin,10.75
Houston,12.5
New Orleans,9.25
Example: When I compare array[0][0] to price[0][0] the strings match therefore I must take the whole ROW of array[0] and multiply each element by that of price[0][1] to update the array.
Now here is my code:
public static String [][] updateString(String[][] array, String[][] prices)
{
String [][] newArray = new String[array.length][];
for(int row = 0; row < array.length; row++)
{
if (array[row][0].equals(prices[row][0]))
{
for(int i = 0; i<array.length; i++)
{
Double d=Double.parseDouble(array[row][i+1]) * Double.parseDouble(prices[row][1]);
newArray[row][i+1] = d.toString();
}
}
}
return newArray;
}
Here are my errors I'm getting:
Exception in thread "main" java.lang.NullPointerException
at assign_1.DansUtilities.updateString(DansUtilities.java:430)
at assign_1.SalesReportGenerator.main(SalesReportGenerator.java:50)
**line 430 is my method. line 50 is where I call it.
new code:
public static String [][] updateString(String[][] array, String[][] prices)
{
for(int row = 0; row < array.length; row++)
{
if (array[row][0].equals(prices[row][0]))
{
for(int i = 0; i<array[row].length; i++)
{
{Double d=Double.parseDouble(array[row][i]) * Double.parseDouble(prices[row][1]);
array[row][i] = d.toString();}
}
}
}
return array;
heres my new errors:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Omaha"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at assign_1.DansUtilities.updateString(DansUtilities.java:429)
at assign_1.SalesReportGenerator.main(SalesReportGenerator.java:50)
NullPointerException can only be thrown if your array is null. Check in the code that is calling the method.
Other notes to improve your code:
you do not need a new array to store values. You can do it in existing array itself.
your inner for loop must be from 1 to the length of current row not the length of the array so it should be something like:
for(int i=1;i<array[row].length;i++)
And use index i instead of i+1 in loop content.
I suggest to create output of your strings, to see whether they are correctly read from files.
private static void outputString2D(String[][] s, String name) {
for ( int i = 0; i < s.length; i++) {
for ( int j = 0; j < s[i].length; j++ ) {
System.out.println(name + " contains at [" + i + "][" + j + "]:\t" + s[i][j]);
}
}
}
Example how I used it:
public static void main(String[] args) {
String[][] str = new String[2][3];
str[0][0] = new String("I am 0,0.");
str[0][1] = new String("I am 0,1.");
str[0][2] = new String("I am 0,2.");
str[1][0] = new String("I am 1,0.");
str[1][1] = new String("I am 1,1.");
str[1][2] = new String("I am 1,2.");
outputString2D(str, "str");
}
Example output:
str contains at [0][0]: I am 0,0.
str contains at [0][1]: I am 0,1.
str contains at [0][2]: I am 0,2.
str contains at [1][0]: I am 1,0.
str contains at [1][1]: I am 1,1.
str contains at [1][2]: I am 1,2.
Provide us the content of your two strings please.

converting string array into int array

this is what i have so far, i need to convert this string array into just an array of integers, the string array looks something like this
wholef[0] = "2 3 4";
wholef[1] = "1 3 4";
wholef[2] = "5 3 5";
wholef[3] = "4 5 6";
wholef[4] = "3 10 2";
these values come from a text file that i read from but now i need to convert this into one big array of integers, im trying to use the split method but im not sure if it will work on this kind of setup. if anyone can give me a better way it would be nice but i just need to convert this into an array of integers, thats really all i need.
for(int k = 0; k < fline; k++)
{
String[] items = wholef[k].replaceAll(" ", "").split(",");
int[] parsed = new int[wholef[k].length];
for (int i = 0; i < wholef[k].length; i++)
{
try
{
parsed[i] = Integer.parseInt(wholef[i]);
} catch (NumberFormatException nfe) {};
}
}
This is the new code im using now, its very close cause i only get one error
int q = 0;
for (String crtLine : wholef)
{
int[] parsed = new int[wholef.length];
String[] items = crtLine.split(" ");
for (String crtItem: items)
{
parsed[q++] = Integer.parse(crtItem);
}
}
the error is this
java:97: error: cannot find symbol parsed[q++} = Integer.parse(crtItem);
^
symbol: method parse(String)
location: class Integer
1 error
Try this:
int i = 0;
for (String crtLine : wholef) {
String[] items = crtLine.split(" ");
for (String crtItem: items) {
parsed[i++] = Integer.parseInt(crtItem);
}
}
This take your string array and dumps it into intwholef[n..total];
If you want it into a 2D array or an object array you have to do some additional. Then you can do an array of objects, and have each set of values as an attribute.
String[] parts = wholef[0].split(" ");
int[] intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++) {
intwholef[n] = Integer.parseInt(parts[n]);
}

rotating string array in java

How would i rotate a string array in java for a tetris game i am making. For example, the string array
[
"JJJJ",
"KKKK",
"UUUU"
]
would become
[
"UKJ",
"UKJ",
"UKJ",
"UKJ"
]
I can do it with a char matrix using this code
public char[][] rotate(char[][] toRotate)
{
char[][] returnChar = new char[toRotate[0].length][toRotate.length];
for(int rows = 0; rows<toRotate.length; rows++)
{
for(int cols = 0; cols<toRotate[0].length; cols++)
{
returnChar[cols][toRotate.length-1-rows]=toRotate[rows][cols];
}
}
return returnChar;
}
With the Array String is similar to want you have done:
public static String[] rotate(String [] toRotate)
{
String [] returnChar = new String[toRotate[0].length()];
String [] result = new String[toRotate[0].length()];
Arrays.fill(returnChar, "");
for(int rows = 0; rows<toRotate.length; rows++)
for(int cols = 0 ; cols < toRotate[rows].length(); cols++)
returnChar[cols] = returnChar[cols] + toRotate[rows].charAt(cols);
for(int i = 0; i < returnChar.length; i++)
result[i] = new StringBuffer(returnChar[i]).reverse().toString();
return result;
}
I go through all char in each String on array toRotate, concat this char (toRotate[rows].charAt(cols)) to each String returnChar[cols] on the array returnChar
Strings are immutable in Java, so you have a few options
Write a wrapper for rotate(char [][]) that turns it back into a string array
Modify the function to create a new array of strings from the input
Create a data structure that holds the data in the most efficient format and then has getters that return it in the format you want it.
3 is essentially what you 'should' be doing. In a Tetris game, you would create a matrix of the size of the game field (possibly padded).
This function does the job of converting the Strings into char[][] so you can use your function.
public static String[] rotateString(String[] toRotate) {
char[][] charStrings = new char[toRotate.length][];
for(int i = 0; i < toRotate.length; i++) {
charStrings[i] = toRotate[i].toCharArray();
}
// This is YOUR rotate function
char[][] rotatedStrings = rotate(charStrings);
String[] returnStrings = new String[rotatedStrings.length];
for(int i = 0; i < rotatedStrings.length; i++) {
returnStrings[i] = new String(rotatedStrings[i]);
}
return returnStrings;
}

Categories

Resources