Converting a string representation of an array into an array in Java - java

I have a string in Java like this:
String s = "{{\"2D\", \"array\"}, {\"represented\", \"in a string\"}}"
How can I convert it into an actual array? Like so:
String[][] a = {{"2D", "array"}, {"represented", "in a string"}}
(What I'm looking for is a solution a bit like python's eval())

I strongly suggest that you use a json capable library to parse your String. However, just for fun, please take a look at the code below, that does the thing you need using only String methods:
String s = "{{\"2D\", \"array\"}, {\"represented\", \"in a string\"}}";
s = s.replace("{", "");
String[] s0 = s.split("},\\s");
int length = s0.length;
String[][] a = new String[length][];
for (int i = 0; i < length; i++) {
a[i] = s0[i].replace("}", "").split(",\\s");
}

Related

Storing objects in ArrayList instead of Array

I currently have a program that stores objects in an array that I need to store in an ArrayList instead.
This is how the objects were originally stored.
private String phrase = "Once upon a time";
private Letter[] letter_array = new Letter[16];
for (int i = 0; i < phrase.length(); i++) {
letter_array[i] = new Letter(phrase.charAt(i));
}
So now, I'm trying to use something like this instead.
private String phrase = "Once upon a time";
ArrayList<Letter> aToZ = new ArrayList<Letter>();
for (int i = 0; i < phrase.length(); i++) {
Letter x = new Letter.charAt(i);
aToZ.add(x);
}
Some of the code has been omitted, but these are the pertinent parts.
This doesn't work and I've tried variations, but I just really don't know how to do this.
Instead of
Letter x = new Letter.charAt(i);
you need
Letter x = new Letter(phrase.charAt(i));
in your 2nd code snippet
Letter x = new Letter(phrase.charAt(i));
You almost had it! You need to include the "phrase." before charAt, but everything else seems to be correct.
Try to think of the object > string > charAt sequence carefully when you reread your code. Ask yourself when you read over your code: "what is it exactly about the object that I want to reference/change?"

Analyse large String using processing

I have a String which I need to split and add to different arrays.
This is my String
{"locations":[{"latitude":"1.3846519","longitude":"103.763276","startTime":"1422720220292","duration":"0","accuracy":"50.981998443604"},{"latitude":"1.3845814","longitude":"103.7634384","startTime":"1422720520181","duration":"0","accuracy":"55.532001495361"},{"latitude":"1.3844195","longitude":"103.763209","startTime":"1422720820265","duration":"0","accuracy":"34.5"},{"latitude":"1.3844051","longitude":"103.7632272","startTime":"1422721120466","duration":"0","accuracy":"36"},
],"success":1}
The output I want is like this in different arrays.
latitudeArray[] = // String array of latitude values
longitudeArray[] = // String array of longitude values
startTimeArray[] = // String array of start time values
durationArray[] = // String array of duration values
accuracyArray[] = // String array of accuracy values
I am using processing IDE to analyse my data and I tried matchAll() and split() functions but couldn't get it work.
Could you please help me in getting my output? Thanks.
Edit: I managed to extract one latitude value but my method seems very inefficient. How can I do this inside a loop?
String[] locationData = loadStrings("sample.txt");
ArrayList<String> latitudeArray = new ArrayList<String>();
ArrayList<String> longitudeArray = new ArrayList<String>();
ArrayList<String> startTimeArray = new ArrayList<String>();
ArrayList<String> durationArray = new ArrayList<String>();
ArrayList<String> accuracyArray = new ArrayList<String>();
String temp;
int index;
index = locationData[0].indexOf("latitude");
println(index);
temp = locationData[0].substring(index+11);
println(temp);
index = temp.indexOf(",");
println(index);
latitudeArray.add(temp.substring(0,(index-1)));
println(latitudeArray.get(0));
Wasn't sure in what format the loadStrings() method returns, so I just used the initial String you provided.
You're heading in the right direction with the string methods. This code tries to benefit from the single input string. If you split on "latitude", then all the elemets in the array, except for the first one, will have the numbers we're interested on in the begining. E.g.: split("latitude\":\"") gives all the latitudes in the begining:
[0] = {"locations":[{"
[1] = 1.3846519","longitude":"103.763276","startTime":"1422720220292","duration":"0","accuracy":"50.981998443604"},{"
[2] = 1.3845814","longitude":"103.7634384","startTime":"1422720520181","duration":"0","accuracy":"55.532001495361"},{"
[3] = 1.3844195","longitude":"103.763209","startTime":"1422720820265","duration":"0","accuracy":"34.5"},{"
[4] = 1.3844051","longitude":"103.7632272","startTime":"1422721120466","duration":"0","accuracy":"36"}, ],"success":1}
To read the actual numbers, we just need to read until the next quote("). Doing indexOf("\"") will give use the position till which we must read to retrieve that number. So, just perform a substring(0,indexOfQuote) on it to get the value. The repeat again, but this time splitting on "longitude" to get them.
Full program:
public static void main(String[] args) {
final String INPUT = "{\"locations\":["
+ "{\"latitude\":\"1.3846519\",\"longitude\":\"103.763276\",\"startTime\":\"1422720220292\",\"duration\":\"0\",\"accuracy\":\"50.981998443604\"},"
+ "{\"latitude\":\"1.3845814\",\"longitude\":\"103.7634384\",\"startTime\":\"1422720520181\",\"duration\":\"0\",\"accuracy\":\"55.532001495361\"},"
+ "{\"latitude\":\"1.3844195\",\"longitude\":\"103.763209\",\"startTime\":\"1422720820265\",\"duration\":\"0\",\"accuracy\":\"34.5\"},"
+ "{\"latitude\":\"1.3844051\",\"longitude\":\"103.7632272\",\"startTime\":\"1422721120466\",\"duration\":\"0\",\"accuracy\":\"36\"},"
+ " ],\"success\":1}";
String latitudeArray[] = splitAndCollect("latitude", INPUT);
String longitudeArray[] = splitAndCollect("longitude", INPUT);
String startTimeArray[] = splitAndCollect("startTime", INPUT);
String durationArray[] = splitAndCollect("duration", INPUT);
String accuracyArray[] = splitAndCollect("accuracy", INPUT);
System.out.println("Done");
}
private static String[] splitAndCollect(String string, String input) {
final String COLON = "\":\"";
String[] split = input.split(string + COLON);
String[] output = new String[split.length - 1];
for (int i = 0; i < output.length; i++)
// Using [i+1] - since split[0] contains "locations".
// Subsequent splits will have the numbers needed.
output[i] = split[i + 1].substring(0, split[i + 1].indexOf("\""));
System.out.println(string + "\n" + Arrays.toString(output));
return output;
}
If you can preprocess the file to csv. file using simple shell script, then do string processing in java, I think you can get better performance. For csv. file processing in Java, refer http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/ (This blog contains simple sample).
If you do some preprocessing step (even in Java) before parsing, you can get all the values to those string arrays simply with one loop. You can use method suggested by Vineet using single loop. So with preprocessing step overall loop count becomes 2.
Thanks,
Mili
It seems that you have data in JSON format. The way you are trying to get data from the is quite difficult (but doable). You can try JSON parser . Its easy to learn and use. You can find one example here.

How can I get textbox value into array and convert into integer in java

I need to get textbox value into array and convert them into integer.
I'm not sure whether should I 1st convert and get into array or get into array and after convert.
Please explain with relevant examples
I've already tied out this code segment. But its wrong according to my knowledge.
String data [] = Integer.parseInt(jTextField1.getText());
String[] stringValues = jTextField1.getText().split("[,]");
int[] numArray= new int[stringValues.length];
for(int i=0; i<numArray.length; i++){
numArray[i]= Integer.parseInt(stringValues[i]);
}
You are trying to assign an single inter to a string array so it will not work.
Because two types are incompatible.
Either you must have an integer array or you can have string array and use string value of the textfield.
e.g.
String []stringData = {jTextField1.getText()};
or
int [] = {Integer.parseInt(jTextField1.getText())};
But since you are using just single value it is better to use an variable rather than an array.
Try this:
String str = "34,56,78,32,45";
String[] parts = str.split(",");
for (int i = 0; i < parts.length; i++)
{
int no=Interger.parse(parts[i]);
//Do your stuff here
}

Can You Put Java Retval Into an Array

I'm scanning through an array of String objects, each string object is going to be broken down into a regex.
When going through a an enhanced for-loop I'm wondering, is it possible to put the retval into an array?
For example if I have String regex = new String[3];
Where regex[0] = "EVEN_BIN_NUM (0|1)*0"
The enhanced for-loop can break my String object up into EVEN_BIN_NUM and (0|1)*0
I want to be able to put EVEN_BIN_NUM in one array, and (0|1)*0 in another array. Here is the code I have that scans through the String array with the string objects
/*
* Run through each String object and appropriately place them in the kind,
* and explicit.
*/
for (int j = 0; j < regex.length; j++)
{
for (String retval: regex[j].split(" ", 2))
{
System.out.println(retval);
}
}
For regex[0].split(" ", 2) I get EVEN_BIN_NUM and (0|1)*0 returned separately.
Alternatively, if you know how to break this up in a better way, let me know:
EVEN_BIN_NUM (0|1)*0
ODD_BIN_NUM (0|1)*1
PET (cat|dog)
The parts in capital letters are to be put in the "kind" array, and the rest is to be put in another array.
So the kind array would have three strings, and the other array would have three strings.
Hopefully this isn't too confusing....
It might be a good idea to use a Map object to store your information, however, if you wanted to return your analysis as an array, you could return an array of arrays and do the following.
String[] regex = {"EVEN_BIN_NUM (0|1)*0", "ODD_BIN_NUM (0|1)*1", "PET (cat|dog)"} ;
String[][] split = new String[regex.length][];
for(int i = 0; i < regex.length; i++) {
split[i] = regex[i].split(" ", 2);
}
You can then access the data as follows
String firstProperty = split[0][0]; //EVEN_BIN_NUM
String firstRegex = split[0][1]; //(0|1)*0
String secondProperty = split[1][0]; //ODD_BIN_NUM
String secondRegex = split[1][1]; //(0|1)*1
etcetera.
Or using a map:
Map<String, Pattern> map = new HashMap<>();
for(int i = 0; i < regex.length; i++) {
String[] splitLine = regex[i].split(" ", 2);
map.put(splitLine[0], Pattern.compile(splitLine[1]));
}
This way your properties would map straight to your Patterns.
For example:
Pattern petPattern = map.get("PET");

Loops and Strings in Java

It appears to me that there could be a better way to this, maybe using loops, I think.
String hora1 = listaH.get(0);
String hora2 = listaH.get(1);
String hora3 = listaH.get(2);
String hora4 = listaH.get(3);
String hora5 = listaH.get(4);
String hora6 = listaH.get(5);
String hora7 = listaH.get(6);
String hora8 = listaH.get(7);
String hora9 = listaH.get(8);
Is there another way to write this using less words?
Thanks
It depends on what you want to achieve and what you hope to gain from it...but...
Assuming that listaH is java.util.List, you could use
for (String horse : listaH) {
System.out.println(horse);
}
(NB: You can do the same thing with arrays)
Take a look at The for statement and The while and do-while statements for more details
Use arrays for hora variable. It can be like
String[] hora = new String[9];
Now you can use any loops, but for is best for your case.
for(int i = 0; i < 9 ; i++){
hora[i] = listaH.get(i);
}
But why waste resource and complexity on new variables? You can do something like listaH.get(4) wherever you need hora5.
Iterator itr = listaH.iterator();
while(itr.hasNext()) {
String element = (String) itr.next();
System.out.print(element + " ");
}
or
for (int i=0;i<listaH.size();i++) {
String element = (String)listaH.get(i);
System.out.print(element + " ");
}
if you need String array then use this one
String[] array = listaH.toArray(new String[listaH.size()]);
Yes. Instead of separate variables for each element, you should just leave them in the original list and then access them that way. So, for example, when you need the value that you are trying to store in hora9, use listaH.get(8) instead.

Categories

Resources