Removing the bracket and empty string - java

The end result of the code is to be able to parse the string array to integer array but as you can see I get an exception. I tried to split the [ and ] signs but when I call the first (0) element splited_game_result[0] of the array, it's returns nothing. What is the solution here? I tried using trim method.
String[] ca_po_pe = {"4:7","PAUSE","2:0","1:3 PINE","PAUSE","CANCEL","2:4","0:5 PINE","PAUSE","CANCEL"};
String canc_postp_pen_games = "";
boolean confirming = true;
for(String looped_games : ca_po_pe) {
if(confirming) { canc_postp_pen_games+=looped_games; confirming=false; }
else { canc_postp_pen_games+=", "+looped_games; } }
System.out.println("LOOPED FINAL RESULT GAMES TO INSERT COMMAS: " + "\n" + canc_postp_pen_games + "\n");
String[] fin_games_res = canc_postp_pen_games.split("[,]");
ArrayList<String> arraylist= new ArrayList<String>();
Collections.addAll(arraylist, fin_games_res);
for (String str: arraylist) {
}
System.out.println("ELEMENTS ADDED TO ARRAYLIST: " + arraylist + "\n");
int noItems = arraylist.size();
for (int i = 0; i < noItems; i++) {
String currItem = arraylist.get(i);
if (currItem.contains("PAUSE")) {
arraylist.add(new String("400"));
noItems++; }
if (currItem.contains("CANCEL")) {
arraylist.add(new String("300"));
noItems++; }
if (currItem.contains(" PINE")) {
arraylist.add(new String("500"));
noItems++; }
}
System.out.println("ELEMENTS BEFORE REMOVAL: " + "\n" + arraylist + "\n");
Iterator<String> iter_getting = arraylist.iterator();
while(iter_getting.hasNext()) {
if(iter_getting.next().contains("PAUSE")){
iter_getting.remove(); }}
Iterator<String> iter_getting1 = arraylist.iterator();
while(iter_getting1.hasNext()) {
if(iter_getting1.next().contains("CANCEL")){
iter_getting1.remove(); }}
Iterator<String> iter_getting2 = arraylist.iterator();
while(iter_getting2.hasNext()) {
if(iter_getting2.next().contains(" PINE")){
iter_getting2.remove(); }}
System.out.println("ELEMENTS AFTER REMOVAL: " + "\n" + arraylist);
System.out.println("ELEMENT ON INDEX 3 BEFORE CONVERTION TO ARRAY: " + "\n" + arraylist.get(3));
String convert = arraylist.toString();
System.out.println("CONVERTED STRING: " + convert);
String[]splited_game_result = convert.trim().split("[\\[:,\\]]");
System.out.println(" AFTER SPLITING TO ARRAY: " + "\n" + splited_game_result[0]);
Integer[] final_result = new Integer[splited_game_result.length];
int g = 0;
for(String fsgr : splited_game_result)
{ final_result[g] = Integer.parseInt(fsgr); g++;}
System.out.println("INTEGER ELEMENT ON INDEX 0: " + "\n" + final_result[1]);

For everybody who wonders, exception is raised in the very end of the source. It says NumberFormatException: For input string: "". See source below:
for(String fsgr : splited_game_result)
{ final_result[g] = Integer.parseInt(fsgr); g++;}
The reason is in the regular expession author used to split the array:
String[]splited_game_result = convert.trim().split("[\\[:,\\]]");
It produces the following array of strings:
["", "4", "7", " 2", "0", " 2", "4", " 400", " 500", " 400", " 300", " 500", " 400", " 300"]
Issue is that Integer.parseInt requires string that contain parsable integer
Possible workaround is to add if condition to ensure your fsgr is not an empty string and doesn't contain whitespaces:
for(String fsgr : splited_game_result) {
String fsgrTrim = fsgr.trim();
if (!fsgrTrim.isEmpty()) {
final_result[g] = Integer.parseInt(fsgrTrim);
g++;
}
}
Or to add try-catch clause:
for(String fsgr : splited_game_result) {
try {
final_result[g] = Integer.parseInt(fsgr);
g++;
} catch (Exception e) {
e.printStackTrace();
}
}

I still don't know what you're trying to do, but here is your exception. You are parsing an empty string and trying to parse a space before the number. Put comments in for your logic.
for (String fsgr : splited_game_result) {
try {
final_result[g] = Integer.parseInt(fsgr);
g++;
} catch(Exception e2) {
System.out.println("Exception = ["+ fsgr + "]");
}
}
Output (in middle of put. Use first and last printlns as location)
CONVERTED STRING: [4:7, 2:0, 2:4, 400, 500, 400, 300, 500, 400, 300]
AFTER SPLITING TO ARRAY:
Exception = []
Exception = [ 2]
Exception = [ 2]
Exception = [ 400]
Exception = [ 500]
Exception = [ 400]
Exception = [ 300]
Exception = [ 500]
Exception = [ 400]
Exception = [ 300]
INTEGER ELEMENT ON INDEX 0:
7

Related

How to filter the string/array by using java

I need a help on below questions. As per the code im getting the below output:
parameter_Name: Raghu
parameter_Name: Kartik
parameter_Name: sundar
But in the content if i have the below format,
content = "Hi {{Raghu}}, this is your {{kartik}} last 4 {{sundar}}. {{each numberdetail}} {{loop_var. ABC}} {{loop_var. DEF}} {{loop_var. GHI}}{{end}}";
So in the above string, if {{each comes, will filter the "{{each" and will take "numberdetail" as seperate array. And if {{loop_var comes,remove loop_var and add ABC in numbderdetail error. If we find {{end}} then we will terminate the array.
Any idea please.
Expected Output:
"Parameter_name": "Raghu",
"Salary": "32.17",
"LineDetail": [{
"ABC": "0",
"DEF": "Device",
"GHI": "792.00"
}]
Code:
public class JavaTest {
public static void main(String[] args) {
String content = "Hi {{Raghu}}, this is your {{kartik}} last 4 {{sundar}}.";
String[] contentArray;
List contentArrayList = new ArrayList();
if (content != null && content.trim() != "" && !content.equals("")) {
contentArray = content.split(" ");
for (String out : contentArray) {
if (!"".equals(out) && out.contains("{{")) {
String parameter_Name = out.substring(out.indexOf("{{") + 2, out.indexOf("}}"));
System.out.println("parameter_Name::" + parameter_Name);
}
}
}
}
}
Well, I think this is what you need.
public class JavaTest {
public static void main(String[] args) {
String content = "Hi {{Raghu}}, this is your {{kartik}} last 4 {{sundar}}. {{each numberdetail}} {{loop_var. ABC}} {{loop_var. DEF}} {{loop_var. GHI}}{{end}}";
Pattern pattern = Pattern.compile("\\{\\{\\w+\\.* *\\w*\\}\\}");
Matcher m = pattern.matcher(content);
List<String> list = new ArrayList<String>();
while (m.find( )) {
list.add(m.group().replaceAll("\\{", "").replaceAll("\\}", ""));
}
boolean insideLoop= false;
for (String current: list){
if (current.startsWith("each")){
insideLoop = true;
System.out.println("Parameter_Name: " + current.split(" ")[1] + ": [{");
} else if (insideLoop){
if (current.startsWith("loop_var.")){
String value = current.split(" ")[1];
System.out.println("\"" + value + "\"");
}else {
if (current.startsWith("end")){
insideLoop = false;
System.out.println("}]");
}
}
}else {
System.out.println("Parameter_Name: " + current);
}
}
}
}
Output is:
Parameter_Name: Raghu
Parameter_Name: kartik
Parameter_Name: sundar
Parameter_Name: numberdetail: [{
"ABC"
"DEF"
"GHI"
}]

java.lang.ArrayIndexOutOfBoundsException :

I have a String = "abc model 123 abcd1862893007509396 abcd2862893007509404", if I provide space between abcd1 & number eg. abcd1 862893007509396 my code will work fine, but if there is no space like abcd1862893007509396, I will get java.lang.ArrayIndexOutOfBoundsException, please help ?:
PFB the code :
String text = "";
final String suppliedKeyword = "abc model 123 abcd1862893007509396 abcd2862893007509404";
String[] keywordarray = null;
String[] keywordarray2 = null;
String modelname = "";
String[] strIMEI = null;
if ( StringUtils.containsIgnoreCase( suppliedKeyword,"model")) {
keywordarray = suppliedKeyword.split("(?i)model");
if (StringUtils.containsIgnoreCase(keywordarray[1], "abcd")) {
keywordarray2 = keywordarray[1].split("(?i)abcd");
modelname = keywordarray2[0].trim();
if (keywordarray[1].trim().contains(" ")) {
strIMEI = keywordarray[1].split(" ");
for (int i = 0; i < strIMEI.length; i++) {
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
}
} else {
text = keywordarray2[1];
}
}
}
After looking at your code the only thing i can consider for cause of error is
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
You are trying to access strIMEI[i+1] which will throw an error if your last element in strIMEI contains "abcd".

NoSuchElementException error

I am trying to see if the next token in a string is equivalent to map key, and adding a message to an array list.
ArrayList<String> trace = new ArrayList<String>();
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
for(String key: expression.keySet())
if(st.nextToken() == key)
trace.add(key + "Changed from " + expression.get(key) + " to " + tokens.get(2));
expression.put(tokens.get(0),Integer.parseInt(tokens.get(2)));
tokens.clear();
}
ERROR MESSAGE
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Commander.main(Commander.java:45)
The problem is with st.nextToken() call.
You are checking st.hasMoreTokens() only once but calling st.nextToken() twice. And it is throwing the error.
During 1st while loop you are reading all the tokens:
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
Since 'all' the tokens are already read, now when you try to read the token again inside the for loop you will get the error.
if(st.nextToken() == key) {
trace.add(key + "Changed from " + expression.get(key) + " to " + tokens.get(2));
}
There is also another potential problem. You are trying to convert the 3rd token to an Integer. It might fail there as well:
// Value of tokens.get(2) is "string"
Integer.parseInt(tokens.get(2))
You will get error here also. It would be good to check if tokens.get(2) is of numeric type or not. like:
int value = 0;
if (StringUtils.isNumeric(tokens.get(2))) {
value = Integer.parseInt(tokens.get(2));
}
// Default value will be 0.
expression.put(tokens.get(0), value);
Reference: StringUtils.isNumeric()
So, the modified code will be like:
ArrayList<String> trace = new ArrayList<String>();
if(!element.startsWith("PRINT")) {
List<String> tokens = new ArrayList<String>();
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
// Size of tokens has to be more then 3, otherwise you will get another error.
if (tokens.size() >= 3) {
for(String key: expression.keySet()) {
if(tokens.get(0).equals(key)) {
// Do your other operations...
trace.add(key + "Changed from " + expression.get(key) + " to " + tokens.get(2));
}
}
// Do some more operations ...
int value = 0;
if (StringUtils.isNumeric(tokens.get(2))) {
value = Integer.parseInt(tokens.get(2));
}
// Default value will be 0.
expression.put(tokens.get(0), value);
}
tokens.clear();
}

Out of bounds array exception for one line and not the other?

CODE
ArrayList<String> tokens = new ArrayList<String>();
ArrayList<String> PRINT = new ArrayList<String>();
String tok = "";
for(String element : list) {
StringTokenizer st = new StringTokenizer(element);
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tok = st.nextToken();
tokens.add(tok);
for(String key : expression.keySet())
if(tok.equals(key))
System.out.println(tokens.get(0) + " changed from " + expression.get(key) + " to " + Integer.parseInt(tokens.get(2)));
}
expression.put(tokens.get(0),Integer.parseInt(tokens.get(2)));
tokens.clear();
}
I am getting an array out of bounds exception at below line
System.out.println(tokens.get(0) + " changed from " + expression.get(key) + " to " + Integer.parseInt(tokens.get(2))
I know that tokens.get(0) = "A", tokens.get(1) = "=" and tokens.get(2) = "7"
Instead of code
for(String element : list) {
StringTokenizer st = new StringTokenizer(element);
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tok = st.nextToken();
tokens.add(tok);
Use below code
for(String element : list) {
for(int i=0;i<element.length();i++){
tokens.add(element.charAt(i)+"");
}
The problem is that the first time you add a token to tokens there will be only one item, however your for loop requires 3 (at indexes 0, 1 and 2).

Can't decode Json array values?

How to get these JSON values in android?
{
"one": [
{
"ID": "100",
"Name": "Hundres"
}
],
"two": [
{
"ID": "200",
"Name": "two hundred"
}
],
"success": 1
}
I tried the following but it shows that the length is 0. I can't get the array values.
JSONObject json = jParser.getJSONFromUrl(url_new);
try {
getcast = json.getJSONArray("one");
int length = getcast.length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use following line in your code
String str = jParser.getJSONFromUrl(url).tostring();
Following is the Code Snippet which worked for me
String str = "{"
+ "\"one\": ["
+ "{"
+ "\"ID\": \"100\","
+ "\"Name\": \"Hundres\""
+ "}"
+ "],"
+ "\"two\": ["
+ " {"
+ " \"ID\": \"200\","
+ " \"Name\": \"two hundred\""
+ " }"
+ "],"
+ "\"success\": 1"
+ "}";
try {
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("one");
int n = arr.length();
String id;
String name;
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
arr = obj.getJSONArray("two");
n = arr.length();
for (int i = 0; i < n; ++i) {
JSONObject person = arr.getJSONObject(i);
id = person.getString("ID");
name = person.getString("Name");
}
int success = obj.getInt("success");
}
catch(Exception ex) {
System.out.println(ex);
}
I guess the failure lies in the first line. What kind of value is url_new?
If you could get the Json from above in form of a String I'd recommend constructing the JSONObject json from the constructor JSONObject(String source) like here:
JSONObject json = new JSONObject(json_string);
That's how I use to extract the JSON from API-calls.
Reference: http://www.json.org/javadoc/org/json/JSONObject.html
You can see all constructors here.

Categories

Resources