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".
Related
I am getting result in the form {a=2 ,b=5} after spel expression evaluation.
I want to convert it to json.
How do I do it?
Please help!
here is your solution:
public static void main(String[] args) {
String something = "{a=2 ,b=5}";
something = something.replace("{", "");
something = something.replace("}", "");
String[] pairs = something.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String pair : pairs) {
list.add(pair);
}
for (int i = 0; i < list.size(); i++) {
String[] temp = list.get(i).split("=");
temp[0] = "\"" + temp[0] + "\"";
list.set(i, temp[0] + ":" + temp[1]);
}
String contents = "";
for (int i = 0; i < list.size(); i++) {
contents = contents + ", " + list.get(i);
}
contents = contents.replaceFirst(", ", "");
contents = "{" + contents + "}";
System.out.println("Contents: " + contents);
}
And here is your result:
Contents: {"a":2 , "b":5}
I am building a tag reader for inventory purpose. Using the for loop to iterate through the tags to count/total the ids. I get an error on my return line "tagsFound cannot be resolved into a variable". How do i use the variable inside the for loop and then access it outside the loop?
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
for (int i=0; i<tagList.length; i++) {
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
String[] tagsFound;
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
public String[] getTags(AlienClass1Reader reader)throws AlienReaderException{
int coneCount = 0;
int drumCount = 0;
// Open a connection to the reader
reader.open();
// Ask the reader to read tags and print them
Tag tagList[] = reader.getTagList();
if (tagList == null) {
System.out.println("No Tags Found");
} else {
System.out.println("Tag(s) found: " + tagList.length);
String[] tagsFound = new String[tagList.length];
for (int i=0; i<tagList.length; i++) {
tagsFound = "";
Tag tag = tagList[i];
System.out.println("ID:" + tag.getTagID() +
", Discovered:" + tag.getDiscoverTime() +
", Last Seen:" + tag.getRenewTime() +
", Antenna:" + tag.getAntenna() +
", Reads:" + tag.getRenewCount()
);
//tagFound[i]= "" + tag.getTagID();
String phrase = tag.getTagID();
tagFound[i] = phrase;
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
if (tokens[0].equals("0CCE") && tokens[3].equals("1001")){drumCount++;}
if (tokens[0].equals("0CCE") && tokens[3].equals("1004")){coneCount++;}
tagsFound[i] = tag.getTagID();
}
System.out.println("Cones= " + coneCount);
System.out.println("Drums= " + drumCount);
// Close the connection
reader.close();
return tagsFound;
}
}
the returned array will have empty strings in the positions where the tag does not satisfy the criteria.
I have a text editor where user can put text like this:
[[PAYMENTS_N]] You have to pay [[amount]]$ before [[date]].[[/PAYMENTS_N]]
[[PAYMENTS_Z]] You didn't pay [[debt]]$ on time: [[ddate]].[[/PAYMENTS_Z]]
And there are XML files that look like this:
<DATA_NZ><USER><ID>12345</ID><COMP_NZ><COMP>
<STATUS>Z</STATUS>
<AMOUNT_NZ>128.01</AMOUNT_NZ>
<DATE_NZ>28.05.2015</DATE_NZ>
<STATUS>N</STATUS>
<AMOUNT_NZ>12.32</AMOUNT_NZ>
<DATE_NZ>21.09.2015</DATE_NZ>
<STATUS>N</STATUS>
<AMOUNT_NZ>12.32</AMOUNT_NZ>
<DATE_NZ>20.10.2015</DATE_NZ>
</COMP></COMP_NZ></USER></DATA_NZ>
Now I want to change the text from editor into something like this:
Remember about your next payments:
You have to pay 12.32$ before 21.09.2015.
You have to pay 12.32$ before 20.10.2015.
You didn't pay 128.01$ on time: 28.05.2015.
And I have this code:
public void parseTags(String content) {
String nOpenTag, nCloseTag;
String zOpenTag, zCloseTag;
String dnTag, knTag, dzTag, kzTag;
nOpenTag = "[[PAYMENTS_N]]";
nCloseTag = "[[/PAYMENTS_N]]";
zOpenTag = "[[PAYMENTS_Z]]";
zCloseTag = "[[/PAYMENTS_Z]]";
dnTag = "[[amount]]";
knTag = "[[date]]";
dzTag = "[[debt]]";
kzTag = "[[ddate]]";
String textToExtract = "";
String textToExtract = "";
String textToReplace = "";
String parsedContent = content;//; = content;
if (content.contains(nOpenTag) || content.contains(zOpenTag)) {
for (int i = 0; i < getXMLContainer("SZUK_XM4.XML").getUsers().size(); i++) {
if (getXMLContainer("SZUK_XM4.XML").getUsers().get(i) != null) { //
contact = consentService.findByContactTypeAndIdNumber(ContactType.EMAIL, getXMLContainer("SZUK_XM4.XML").getUsers().get(i).getIdNumber());
payments = getXMLContainer("SZUK_XM4.XML").getUsers().get(i).getPaymentContainer().getPayments();
if (contact.size() > 0) {
StringBuilder strB = new StringBuilder();
StringBuilder strB2 = new StringBuilder();
String textToReplace;
for (int c = 0; c < contact.size(); c++) {
strB.setLength(0);
for (int p = 0; p < payments.size(); p++) {
if (payments.get(p).getStatus().contains("N")) {
textToExtract = content.substring(content.indexOf(nOpenTag) + nOpenTag.length(), content.indexOf(nCloseTag));
textToReplace = textToExtract.replace(dnTag, "Day " + payments.get(p).getPaymentDate());
textToReplace = textToReplace.replace(knTag, "Amount " + payments.get(p).getPaymentAmount());
strB.append(textToReplace);
parsedContent = content.replace(textToExtract, strB.toString());
}
if (payments.get(p).getStatus().contains("Z")) {
textToExtract = parsedContent.substring(parsedContent.indexOf(zOpenTag) + zOpenTag.length(), parsedContent.indexOf(zCloseTag));
textToReplace = textToExtract.replace(dzTag, "Day " + payments.get(p).getPaymentDate());
textToReplace = textToReplace.replace(kzTag, "Amount " + payments.get(p).getPaymentAmount());
strB2.append(textToReplace);
parsedContent = parsedContent.replace(textToExtract, strB2.toString());
}
}
mailService.sendTemplateMail(contact.get(c).getContact(), parsedContent);
}
}
}
}
}
}
This code is supposed to find in the database user with given ID from XML.
If user exists then it reads all the data between and replaces [[TAGS]] from the text editor. After everything's done, it should send an email with replaced text.
The problem is that the text it sends isn't correctly replaced. It gives
Remember about your next payments: You have to pay 12.32$ before
21.09.2015. You have to pay 12.32$ before 20.10.2015.
You didn't pay [[debt]]$ on time: [[ddate]].
See the difference in the last line?
I'm using JAXB to read XML, if it matters.
Hope you can help me! Thanks.
replace:
parsedContent = content.replace(textToExtract, strB.toString());
with:
parsedContent = parsedContent.replace(textToExtract, strB.toString());
I am trying to build a string recursively but it isn't quite working
my code looks like this
public void UpdatePrintList(ArrayList<Node> closedList, ArrayList<Node> openList)
{
if(count <= iterations)
{
String line1 = "";
for(int i = 0; i < closedList.size(); i++)
{
if(i > 0)
{
line1 = line1 + "-";
}
line1 = line1 + closedList.get(i).GetMovement();
}
line1 = line1 + " " + closedList.get(closedList.size()-1).GetG() + " " + closedList.get(closedList.size()-1).GetHeuristic() + " " + closedList.get(closedList.size()-1).GetF();
printList.add(line1);
//*****************************************************************
String line2 = "OPEN ";
for(int i = 0; i < openList.size(); i++)
{
line2 = FindEarlierNode(openList.get(i), line2);
}
System.out.println(line2);
}
count++;
}
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
else
{
FindEarlierNode(varNode.OpenedBy(), varString);
}
varString = varString + varNode.GetMovement() + "-";
return varString;
}
The strange thing is that I know that this if statement
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
runs correctly, so the function does reach the earliest node. But it doesnt add to the string. The code runs but returns nothing. GetMovement just returns a one or two character string. The output should look like this:
OPEN S-R S-RD S-D
But instead it looks like this:
OPEN D-DL-L-
Can anyone help?
Managed to work it out. This gives me my desired output:
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() != null)
{
varString = varString + varNode.GetMovement() + "-";
return FindEarlierNode(varNode.OpenedBy(), varString);
}
return varString += varNode.GetMovement() + " ";
}
thanks everyone.
I have this:
for (String[] aZkratkyArray1 : zkratkyArray) {
String oldString = " " + aZkratkyArray1[0] + " ";
String firstString = aZkratkyArray1[0] + " ";
String newString = " " + aZkratkyArray1[1] + " ";
System.out.println(newString);
System.out.println(fileContentsSingle);
fileContentsSingle = fileContentsSingle.replaceAll(oldString, newString);
if (fileContentsSingle.startsWith(firstString)) {
fileContentsSingle = aZkratkyArray1[1] + " " + fileContentsSingle.substring(firstString.length(),fileContentsSingle.length());
}
}
fileContentsSingle is just some regular string, aZkratkyArray is array with shortened words, f.e.:
ht, hello there
wru, who are you
So when fileContentsSingle = ht I am robot
it should end up : hello there I am robot
or when fileContentsSingle = I am robot hru
it should end up : I am robot who are you
But when I sysout fileContentsSingle after this iteration, or during it, string is never changed.
I tried both replace and replaceAll, I tried probably everything I could think of.
Where is the mistake?
EDIT:
This is how I import array:
String[][] zkratkyArray;
try {
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("zkratky.csv"));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
lineNumberReader.close();
FileReader fileReader = new FileReader("zkratky.csv");
BufferedReader reader = new BufferedReader(fileReader);
zkratkyArray = new String[lines + 1][2];
String line;
int row = 0;
while ((line = reader.readLine()) != null) {
String[] array = line.split(",");
for (int i = 0; i < array.length; i++) {
zkratkyArray[row][i] = array[i];
}
row++;
}
reader.close();
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("Soubor se zkratkami nenalezen.");
zkratkyArray = new String[0][0];
}
Your code will work correctly for "ht I am robot". If you print fileContentsSingle after your for loop, it will print what you expect it to print:
final String[][] zkratkyArray = new String[2][];
zkratkyArray[0] = new String[] { "ht", "hello there" };
zkratkyArray[1] = new String[] { "wru", "who are you" };
String fileContentsSingle = "ht I am robot";
for (String[] aZkratkyArray1 : zkratkyArray) {
String oldString = " " + aZkratkyArray1[0] + " ";
String firstString = aZkratkyArray1[0] + " ";
String newString = " " + aZkratkyArray1[1] + " ";
fileContentsSingle = fileContentsSingle.replaceAll(oldString, newString);
if (fileContentsSingle.startsWith(firstString)) {
fileContentsSingle = aZkratkyArray1[1] + " "
+ fileContentsSingle.substring(firstString.length(), fileContentsSingle.length());
}
}
System.out.println(fileContentsSingle); // prints "hello there I am robot"
Concerning "I am robot hru", it will not work because "hru" is at the end of the String, and not followed by a space, and the String you are replacing is " hru " (with spaces before and after).
As you don't use regexps, you don't need replaceAll(), and you can use replace() instead.
Using regexps, you can do a more generic solution working everywhere in the line:
final String[][] zkratkyArray = new String[2][];
zkratkyArray[0] = new String[] { "ht", "hello there" };
zkratkyArray[1] = new String[] { "wru", "who are you" };
String fileContentsSingle = "ht I am robot wru";
for (String[] aZkratkyArray1 : zkratkyArray) {
fileContentsSingle = fileContentsSingle.replaceAll("\\b" + Pattern.quote(aZkratkyArray1[0]) + "\\b",
Matcher.quoteReplacement(aZkratkyArray1[1]));
}
System.out.println(fileContentsSingle); // hello there I am robot who are you
I don't think you are using any regex here. You are just reading a suustring and replace it with another one.
Just use the other version which does not use regex:
fileContentsSingle.replace(oldString, newString);
In the end, I found out that I had BOM's in input.csv file.