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.
Related
What i am trying to achieve is, let's say I've these variables below:
String num1 = "blah1";
String num2 = "blah2";
String num3 = "blah3";
String num4 = "blah4";
String num5 = "blah5";
Now i want to create a single string variable which would iterate the all values of string's variable inside loop.
for(int i=0; i<=5; i++){
System.out.println(num+""+i); //I know, this would give me some errors. But i want to make something like this to call all string variables.
}
Here i want to print all the values of string's variable by using loop, How to achieve this?
Help would be appreciated!
This is a use case for an array:
String nums[] = new String[] {
"blah1",
"blah2",
"blah3",
"blah4",
"blah5"
}
And then you can easily iterate through the values (note that you don't need to duplicate the number of elements (5) ):
for(int i=0; i<nums.length; i++) {
System.out.println(nums[i]);
}
More about arrays in the Oracle tutorial.
Alternatively, you may use a List instead of an array.
What you need is an Array - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An Array is a container containing a fixed number of values that are the same type, eg:
String [] nums = new String[5];
The above line creates a array called nums of type String which can hold 5 individual String values (they are initially null).
Another way to declare this would be to use:
String [] alt_nums = {"blah1","blah2","blah3","blah4","blah5"};
This set's each value stored in alt_nums to a specific value as declared in the curly braces.
To iterate through an Array you can use an iterative for loop
for(int i = 0; i < alt_nums.length; i++) {
System.out.println(alt_nums[i]);
}
or you can use an enhanced for loop which does this automatically.
for(String num : alt_nums) {
System.out.println(num);
}
You can also use java 8:
List<String> strings = Arrays.asList("sad", "asdf");
strings.forEach(str -> System.out.println(str));
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.
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");
I wanted to store a value from a string array to another string array. But I get "NullPointerException" error with the code below. "imagesSelected" is a string array stored with values inside. But when i wanted to move it into another string array after substring, I get error. I believed is because of the last line of code. I'm not sure how to make it work.
String[] imageLocation;
if(imagesSelected.length >0){
for(int i=0;i<imagesSelected.length;i++){
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
You need to do something like this:
String[] imageLocation = new String[imagesSelected.length];
Otherwise imageLocation will be null.
By the way, you don't need the if around your loop. It's completely redundant, as that will be the same logic that will be used at the start of the loop.
imageLocation[i]
have you initialized imageLocation?
I believe this error is because you are trying to point to a location in the string array that does not exist. imageLocation[0,1,2,3...etc] do not exist yet because the string array has not been initialized.
Try String[] imageLocation[however long you want the array to be]
You must allocate memory for imageLocation.
imageLocation = new String[LENGTH];
Your final solution code should be like as below, or compiler will give you an error that imageLocation may not have been initialized
String[] imageLocation = new String[imagesSelected != null ? imagesSelected.length : 0];
if (imagesSelected.length > 0) {
for (int i = 0; i < imagesSelected.length; i++) {
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
look at this code
String[] imageLocation;
if(imagesSelected.length >0){
imageLocation = new String[imageSelected.length];
for(int i=0;i<imagesSelected.length;i++){
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
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");
}