I have this text field inside a dialog
dialog.setSize(350,350);
dialog.getContentPane().add(BorderLayout.CENTER,
new JTextField(text));
My goal is when user adds multiple strings inside that text field, to extract the text and split it into strings, and then be able to search in a DB for each string like this:
var res = request_handler.search(
"SELECT Name, ingredients FROM " +
"food WHERE FIND_IN_SET('"+containerObj+"',ingredients)");
I'm thinking for something like this:
String foodSearch = ActionField.getText();
int index = 0;
//create a contaner for the strings
ArrayList<String> container = new ArrayList<>();
container.add("");
//loop until end of string
while(index <= foodSearch.length()){
//if we aren't at new string
if(foodSearch.charAt(index) != ','){
//get the char
char temp = foodSearch.charAt(index);
//then append that char to the String in the container
}
else{
container.add("");
}
++index;
}
Basically will use the comma sign as a separation between the strings, looping thru the whole object. But is there a better way of approaching and solving this problem?
Related
I have been given an API that saves data in a field in the following order: ["Hello","world","confused"] .
I don't know how to format like this before I pass my data as an input?
The text values are taken from a checkbox.
If I save it in an array I get "[hello,world,confused]" format.
You save the raw values into a single String. YOu have to save it as an array, list or a map. I will not show map usage in this answer. Example:
//Get the Strings
String ex1 = "hello";
String ex2 = "world";
String ex3 = "confused";
//Array
String[] s = new String[3];
s[0] = ex1;
s[1] = ex2;
s[2] = ex3;
//List
List<String> list = new ArrayList<>();
list.add(ex1);
list.add(ex2);
list.add(ex3);
Now, if you send it over the internet and receive the data, send it as raw strings. Then convert it to List for easability. If the amount of Strings vary, this is the easiest way:
StringBuilder sb = new StringBuilder();
sb.append("[\"");
for(int i = 0; i < list.size()/*or .length if it is an array*/; i++){
if(i == list.size() - 1)
sb.append(list.get(i)/*or array[i]*/ + "\"]");
else
sb.append(list.get(i)/*or array[i]*/ + "\",\"");
}
String f = sb.toString();
//Display list: TextView, print to console, whatever you want to do
These are put in a List because it is much easier to loop a list than to manually add every String.
If the amount of Strings are static, you can use String.format:
String f = String.format(Locale.ENGLISH, "[\"%s\",\"%s\",\"%s\"]", ex1, ex2, ex3);
If I somehow misunderstood your question, let me know so I can edit my answer
I have the following String data that contain arraylist of objects data,How can i convert it to arraylist type
String data="[Score{id=1, value='3.5'},
Score{id=2, value='4.5'},
Score{id=3, value='2.0'}]";
I would omit the brackets [] at start by cutting out the first and last character. Then you have to split the String to get all the objects in an array. At the end you have to convert the String objects to the actual Score classes. You can do that by the same principle, using substring and indexOf methods.
In terms of code, this would look something like this:
// the String containing all the objects
String data="[Score{id=1, value='3.5'}, Score{id=2, value='4.5'}, Score{id=3, value='2.0'}]";
// Cutting out the brackets []
data = data.substring(1, data.length - 1);
// Splitting the String to smaller pieces
// like "Score{id=1, value='3.5'}", etc
String[] array = data.split(",");
// Creating the ArrayList, where we will save the scores
List<Score> scores = new ArrayList<Score>();
for(int i=0;i<array.length;i++) {
// Creating the Score instance
Score score = new Score();
// Omitting the brackets {}
int start = array[i].indefOx("{") + 1;
int end = array[i].indefOx("}");
// Cutting out the String inside brackets {}
String temp = array[i].substring(start, end);
// We use the same principles again to get those values inside the brackets {}.
String[] tempArray = temp.split(",");
for(int j=0;j<tempArray.length;j++) {
int start = array[i].indefOx("=") + 1;
temp2 = tempArray[j].substring(start);
if(j == 0) {
score.setId(Integer.valueOf(temp2));
} else {
// To cut out the ''
score.setValue(temp2.substring(1, temp2.length));
}
}
// adding score instance to the list
scores.add(score);
}
I would just point out that you would have to verify I used the right indexes, when I used substring and indexOf. If this String would be without the "Score" substring, you would be able to convert this more easily, because then the String would represent a JSONArray.
Say you have a text file with "abcdefghijklmnop" and you have to add 3 characters at a time to an array list of type string. So the first cell of the array list would have "abc", the second would have "def" and so on until all the characters are inputted.
public ArrayList<String> returnArray()throws FileNotFoundException
{
int i = 0
private ArrayList<String> list = new ArrayList<String>();
Scanner scanCharacters = new Scanner(file);
while (scanCharacters.hasNext())
{
list.add(scanCharacters.next().substring(i,i+3);
i+= 3;
}
scanCharacters.close();
return characters;
}
Please use the below code,
ArrayList<String> list = new ArrayList<String>();
int i = 0;
int x = 0;
Scanner scanCharacters = new Scanner(file);
scanCharacters.useDelimiter(System.getProperty("line.separator"));
String finalString = "";
while (scanCharacters.hasNext()) {
String[] tokens = scanCharacters.next().split("\t");
for (String str : tokens) {
finalString = StringUtils.deleteWhitespace(str);
for (i = 0; i < finalString.length(); i = i + 3) {
x = i + 3;
if (x < finalString.length()) {
list.add(finalString.substring(i, i + 3));
} else {
list.add(finalString.substring(i, finalString.length()));
}
}
}
}
System.out.println("list" + list);
Here i have used StringUtils.deleteWhitespace(str) of Apache String Utils to delete the blank space from the file tokens.and the if condition inside for loop to check the substring for three char is available in the string if its not then whatever character are left it will go to the list.My text file contains the below strings
asdfcshgfser ajsnsdxs in first line and in second line
sasdsd fghfdgfd
after executing the program result are as,
list[asd, fcs, hgf, ser, ajs, nsd, xs, sas, dsd, fgh, fdg, fd]
public ArrayList<String> returnArray()throws FileNotFoundException
{
private ArrayList<String> list = new ArrayList<String>();
Scanner scanCharacters = new Scanner(file);
String temp = "";
while (scanCharacters.hasNext())
{
temp+=scanCharacters.next();
}
while(temp.length() > 2){
list.add(temp.substring(0,3));
temp = temp.substring(3);
}
if(temp.length()>0){
list.add(temp);
}
scanCharacters.close();
return list;
}
In this example I read in all of the data from the file, and then parse it in groups of three. Scanner can never backtrack so using next will leave out some of the data the way you're using it. You are going to get groups of words (which are separated by spaces, Java's default delimiter) and then sub-stringing the first 3 letters off.
IE:
ALEXCY WOWZAMAN
Would give you:
ALE and WOW
The way my example works is it gets all of the letters in one string and continuously sub strings off letters of three until there are no more, and finally, it adds the remainders. Like the others have said, it would be good to read up on a different data parser such as BufferedReader. In addition, I suggest you research substrings and Scanner if you want to continue to use your current method.
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");