I'm building a small app which auto translates boolean queries in Java.
This is the code to find if the query string contains a certain word and if so, it replaces it with the translated value.
int howmanytimes = originalValues.size();
for (int y = 0; y < howmanytimes; y++) {
String originalWord = originalValues.get(y);
System.out.println("original Word = " + originalWord);
if (toReplace.contains(" " + originalWord.toLowerCase() + " ")
|| toCheck.contains('"' + originalWord.toLowerCase() + '"')) {
toReplace = toReplace.replace(originalWord, translatedValues.get(y).toLowerCase());
System.out.println("replaced " + originalWord + " with " + translatedValues.get(y).toLowerCase());
}
System.out.println("to Replace inside loop " + toReplace);
}
The problem is when a query has, for example, '(mykeyword OR "blue mykeyword")' and the translated values are different, for example, mykeyword translates to elpalavra and "blue mykeyword" translates to "elpalavra azul". What happens in this case is that the result string will be '(elpalavra OR "blue elpalavra")' when it should be '(elpalavra OR "elpalavra azul")' . I understand that in the first loop it replaces all keywords and in the second it no longer contains the original value it should for translation.
How can I fix this?
Thank you
you can sort originalValues by size desc. And after that loop through them.
This way you first replace "blue mykeyword" and only after you replace "mykeyword"
The "toCheck" variable is not explained what is for, and in any case the way it is used looks weird (to me at least).
Keeping that aside, one way to answer your request could be this (based only on the requirements you specified):
sort your originalValues, so that the ones with more words are first. The ones that have same number of words, should be ordered from more length to less.
Related
I'm creating a number of objects with details read in from an array. They will have a standard format for one of their instance variables which I'd like to be, in part, an ascending number. Specifically, I'm creating a load of Location objects which I'd like to have a description of "Flat 1", "Flat 2", etc.
I'm wondering though if there is an easy way to perform addition when assigning a value to a String. Stripped down to the relevant part, my code is:
int size = locations.size();
Location l;
for (int i=0; i<size; i++){
l = new Location ("Flat " + i + 1); //LINE A
addLocation(l);
}
//several bits of code have been removed and swapped around here, I realise
//that that snippet doesn't really perform anything useful
However, Java interprets both the "+" symbols in LINE A as concatenation meaning I get "Flat 01", "Flat 11", "Flat 21", etc.
Obviously I could change around the way the loop works, but I was curious as to whether performing calculations in a myString = value + 2 type statement was possible?
String concatenation is left-associative, so all you have to do is wrap the value you want in parentheses to ensure that it's calculated first:
l = new Location ("Flat " + i + 1);
is effectively:
l = new Location (("Flat " + i) + 1);
So i is appended to the string "Flat " first; and then 1 is appended to that.
Should be:
l = new Location ("Flat " + (i + 1));
Use parentheses:
l = new Location ("Flat " + (i + 1)); //LINE A
I am using .equals for String comparison below, but x does not match "OU":
String memberOfValue="CN=cn,OU=ou,OU=roles,OU=de,OU=apps,DC=meta,DC=cc,DC=com";
String[] pairs = memberOfValue.split(",");
for (int i=0;i<pairs.length;i++) {
String pair = pairs[i];
String[] keyValue = pair.split("=");
System.out.println(keyValue[0]);
String x = keyValue[0];
String y = "OU";
System.out.println(x);
System.out.println(x.equals(y));
}
Where am I going wrong?
Adding these two lines of code shows the problem:
System.out.println("x: " + x + " - " + x.chars().boxed().collect(Collectors.toList()));
System.out.println("y: " + y + " - " + y.chars().boxed().collect(Collectors.toList()));
It gives
x: OU - [8203, 79, 85]
y: OU - [79, 85]
Which shows that you have some invisible char whose integer value is 8203 (zero width space, see What's HTML character code 8203?) in your string. Not sure how you got that.
As #JB Nizet says, you have non-printable characters in your memberOfValue variable, there are some types of characters as for example:
control, format, private use, surrogate, unassigned, etc...
Here is the complete list: http://www.fileformat.info/info/unicode/category/index.htm
In these cases, you can remove all characters from your string using this regular expression: \\P{Print}
For example:
String x = keyValue[0].replaceAll("[\\P{Print}", "");
When you compare the strings again, the result will be correct.
There are two possible problems from what I'm seeing.
A.) If the strings are capitalized differently they will not return equal unless you use the method .equalsIgnoreCase() instead of .equals()
B.) You're not getting the right strings that you're expecting. Be sure to print out or debug which string is getting parsed through.
public enum Number {
one(), two(), three(), four();
}
I want to send a message with the numbers separated by a comma:
The numbers are one, two, three and four
The simplest solution would be to use the method name() in your enum
System.out.println(Number.one.name() + ", "
+ Number.two.name() + ", "
+ Number.three.name() + ", "
+ Number.four.name());
Or, if you want to populate your enum in a List first, because your numbers are many, you could populate them using EnumSet.allOf like this:
List<Number> numberList =
new ArrayList<Number>(EnumSet.allOf(Number.class));
And then simply use it like this:
for (int i = 0; i < numberList.size(); i++){
System.out.print(numberList.get(i).name() + (i == numberList.size() - 1 ? "" : ","));
}
(A little syntatical sugar to distinguish between the last number and the rests are added)
I suggest you read the java documentation here:
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
I'm attempting to write some code for a game in Java, however one of the if statements isn't working as expected.
if(player.gety() < y+row*tileSize){
player.draw(g);
System.out.println("Row: " + y+row*tileSize);
System.out.println("Player: " + player.gety());
}
When this code is run the output that I receive is:
Player: 200
Row: -79.99999999968651320
Player: 200
Row: -79.99999999968651320
Player: 200
Row: -79.99999999968651320
This doesn't make much sense as player.gety() is clearly larger than y+row*tileSize. Is there any reason why this would be happening?
String concatenation is what's tripping you up here. Specifically,
"Row: " + y+row*tileSize
is not the same thing as
"Row: " + (y+row*tileSize)
In the first case, you're getting
("Row: " + y)+ (row*tileSize)
where y is being converted to its String representation and concatenated onto "Row: ", and then the product of row * tileSize is getting converted to its String representation and concatenated onto that.
In the second case, you'd be getting (y + row * tileSize), a single numeric value, which would then be turned into a String representation and concatenated onto the String "Row: :"
This is actually behaving as demanded by the spec. When either operand of the + operator is a String, it no longer means "addition", it means "concatenation", and concatenation does not obey the arithmetical rules of precedence. Instead, it greedily coerces its other operand to a String value and cats the two together.
This can have some unexpected results, as you've discovered. Try adding the parens as suggested above, or printing out the values of the variables individually:
System.out.println("y = "+ y + " row = "+row + " tileSize = " + tileSize)
and it'll be easier to see what's happening.
EDIT:
I expect that you'll find that More likely, y = -79.999999999 (ie, -79.9, repeating) and row*tileSize=68651320. Adding those up you get substantially more than 200.
Yes, I don't think the Row output statement is showing what you think it's showing. Also, might player.draw(g) modify the result of player.gety()? Put the output statements first in the if-true block. Output each variable instead of an expression.
I might have overlooked some factors influencing the process but that is why i seek help here. It is my first post here and i have read the initial prescriptions for helping me getting the best question as a basis for the best answer. I hop you will understand(otherwise please make a comment with further questions)
The case is that i have been creating an ArrayList
ArrayList<String> liste = new ArrayList<String>();
I gather several names, quantities, and dates:
if(shepherd == 0) {
} else if(shepherd <= 0) {
System.out.println(shepherd);
String s = "('shepherd'," + "'" + shepherd + "'," +"'" + ft.format(date) + "'" + ")";
liste.add(s);
}
I have defined shepherd as follows:
double shepherd = 0;
Next, I wish to add these entries to my MySql database.
I construct a query, and print it out so that I can verify that it is of the correct format:
System.out.println("INSERT INTO kennel VALUES");
for(int i = 0; i < liste.size(); i++) {
System.out.println(liste.get(i));
if(i != liste.size()-1) {
System.out.println(",");
}
}
This shows the correct command, with the proper syntax, but it's only output to the console at this point.
I have to send this through some Jsch or Ganymed. Most likely as a String. So i am wondering how i could take all the different parts, the doubles, the strings, the loop and build up a String, identical to the printed line i get in console.
I sensed it would look like this:
String command = (mysql -e "use kennel;insert into department3 values ('shepherd','1','2013-03-04');";
I believe that I am having some trouble with the " and ( and '.
I hope i made it clear what the trouble is about. Thank you in advance. Sincerely
Your string need to be held within quotation marks. Because this will interfere with the quotation marks within your String, you need to escape them. You can do this by placing a backslash in front of the character. :)
String command = "(mysql -e \"use kennel;insert into department3 values ('shepherd','1','2013-03-04');\"";