Convert a string into a multidimensional arrays with different lengths - java

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!

Related

How to print additional arrays? [duplicate]

I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.
Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.
By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);
u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.

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]

Is there a way of traversing from string to int array and vice versa

In Java, given the array
int a[] = {1,2,3}
I can do Arrays.toString(a) to get
"[1,2,3]"
Is there an equally convenient way to return this String back to its antecedent array?
Or must I go through the whole split, for-loop, parseInt stuff?
UPDATE
Thanks everyone for all the thoughts. I rolled out my own function as
String src[] = data.split("\\D+");//data is intArrayAsString: [1,2,3]
int[] nums = new int[src.length - 1];
int ndx = 0;
for (String s : src) {
try {
nums[ndx] = Integer.parseInt(s);
ndx++;
} catch (NumberFormatException e) {
}
}
return nums;
Note: the word traverse seems to have thrown a few people off. By "traversing" I meant the ability to move back and forth from the string to the int array.
As far as i know, no.
But it's easy to do using Split.
I just did this, if you don't understand how to do it:
int[] arr = {1, 2, 3, 4};
String toString = Arrays.toString(arr);
System.out.println(toString);
// we know it starts with [ and ] so we skip it
String[] items = toString.substring(1, toString.length() - 1).split(",");
int[] arr2 = new int[items.length];
for (int i = 0; i < items.length; ++i)
{
arr2[i] = Integer.parseInt(items[i].trim()); // .trim() because it adds the space and parseInt don't like spaces
}
System.out.println(Arrays.toString(arr2));
(free to improve it, it's just a draft)
I don't know of any existing method, so I wrote you my own version:
import java.util.Arrays;
public class ArrayToString {
public static void main(String[] args) {
int a[] = {1,2,3};
String serialized = Arrays.toString(a);
System.out.println(serialized);
int[] b = stringToIntArray(serialized);
System.out.println(Arrays.toString(b));
}
private static int[] stringToIntArray(String serialized) {
// remove '[' and ']'
String raw = serialized.replaceAll("^\\[(.*)\\]$", "$1");
// split by separators
String[] splitStrings = raw.split(", ");
// create new int array
int[] b = new int[splitStrings.length];
for (int i = 0; i < splitStrings.length; i++) {
String splitString = splitStrings[i];
// parse each text individually
b[i] = Integer.parseInt(splitString);
}
return b;
}
}

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]);
}

List<String> ----> to int [ ] [ ] arr

Well I have been stumped as to the best way to do this, I have written the code to read in lines of code from txt files as List. I can then print specific parts or convert this to an array of objects. But, ultimately I would like to have just a 2d int array you can see often in C/C++. I am very green when it comes to java, having only started earlier this week. I have like it up until this point of making dynamic 2d arrays at run time. Can any of you suggest a good way to get to a 2d int array from where i am currently stuck. I was just about to convert it to a char array using 'toChar', then to take the (value#index-48) and store it in its corresponding spot, but that seems pretty ghetto to me.
====updated==========================
eh, thanks for all the replies, but I just figured out how to do it using doubles, so for anyone else, here you go. I would still rather have int, since I have already built my other matrixops classes using this type, but Double shouldn't be an issue i guess.
package uaa.cse215;
import java.io.*;
import java.util.*;
public class ReadMatrix {
private Double[][] A;
private Double[][] B;
private int count;
public int filedir(String matrix) throws Exception{
Double[][] Temp;
String[] arr;
BufferedReader rd = new BufferedReader(new FileReader(matrix));
String s;
List<String> textFile = new ArrayList<String>();
while ((s=rd.readLine())!=null) {
textFile.add(s);
}
String splitarray[] = textFile.get(0).split(" ");//run once to grab # cols
int rows = textFile.size();//number of rows
int cols = splitarray.length;//number of cols
Temp = new Double[rows][cols]; // now can initiate array
for (int i=0; i<rows; i++) {
s = textFile.get(i);
arr = s.split(" ");
for (int j=0; j<cols; j++) {
Temp[i][j] = Double.parseDouble(arr[j]);
}
}
count++;
if (count == 1){
A = Temp;
}
else
B = Temp;
rd.close();
return(1);
}
}
Please note that Java has the char data type which is a 16bit unsigned integer holding a UTF-16 code point. int is in Java always a signed 32 bit integer. So if you want a C like Arrays of chars representing the content of a String, you should use a char[][]
To convert the content of your List<String> into a 2d array you can use the following code:
char[][] twoDarray = new char[textFile.size()];
for(int i = 0; i < textFile.size(); i+)
{
twoDarray[i] = textFile.get(i).toCharArray();
}
The array twoDarray then contains all Strings each as a char array.
This line won't compile
splitarray[j] = textFile.get(i).split(" ");
as splitarray[j] is of type String and split returns an array of Strings
Do the following instead:
for(int row=0;row<textFile.size();row++){
String[] splitarray = textFile.get(row).split(" ");
for(int col=0;col<splitarray.length;col++){
tmp[row][col] = Integer.parse(splitarray[col]);
}
}
if the input matrix dimentions are dynamic or jagged you can use
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
to read numbers and than copy it to raw 2d array if you want.
java.util.Scanner has many handy methods for reading "typed" data from input
Here's an example reading file to 2D array
public static int[][] read2DArray(String fileName) throws FileNotFoundException {
Scanner sc = null;
List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
int columnCount = 0;
int[][] arr = null;
try {
sc = new Scanner(new File(fileName));
while (sc.hasNextLine()) {
// Read line
String line = sc.nextLine();
// Split it
String[] nums = line.split(" ");
if (nums.length > columnCount) {
columnCount = nums.length;
}
// Convert to integers and add to list
list.add(new ArrayList<Integer>());
for (String n : nums) {
list.get(list.size() - 1).add(new Integer(n));
}
}
// Convert list to array
int rowCount = list.size();
arr = new int[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < list.get(i).size(); j++) {
arr[i][j] = list.get(i).get(j);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return arr;
}
Assuming your data file contains ascii-represented numbers that you want parsed into integers:
11 -9 13
12 55 102
1 1 1024
Then you can use the Integer(String s) constructor to parse your string objects.
Also, I suggest splitting each row only once. It won't matter much for small arrays, but the larger your inputs get, the more you'll needlessly recompute the splits.
An (untested) re-writing:
int tmp[][] = new int [rows][cols];
for(int i=0;i<rows;i++){
splitarray = textFile.get(i).split(" ");
for(int j=0;j<cols;j++){
tmp[i][j] = Integer(splitarray[j]);
}
}

Categories

Resources