Sorry for the unclear title but I don't even know what to call it, I'll just go ahead and explain what's happening.
I'm using a Stringbuffer to build an URL. It looks like this:
http://maps.googleapis.com/maps/api/geocode/json?latlng=49.0516736,8.38891840&sensor=false
I encountered this behavious when comparing this string in a Unit-test to the actual result of the method.
And this is the assertion-error I'm getting:
latlng=49.0516736[,8.38891840]&sensor=false> but was:<...on?latlng=49.0516736[,8.3889184]&sensor=false
The emphasis is on the character sequence 0]& and 4]& right before sensor=false
IF I remove the zero before the & the test goes green.
then the created string looks like this:
latlng=49.0516736,8.3889184&sensor=false
so ... just as expected.
It's not the problem, that the 0 itself gets truncated and test would fail - I've proved that my code is doing what it's supposed to (when I remove the zero), but I want to know what is happening here.
0& must be some kind of indication for array-access or some kind of escaping. I don't know.
Anyone any idea what's causing this behaviour?
Edit:
Here's the code I'm using
StringBuffer s = new StringBuffer( grailsApplication.config.geocodingurl.toString() )
s.append(coordinates.latitude)
s.append(",")
s.append(coordinates.longitude)
s.append("&sensor=false")
return s.toString()
There is a formatting/padding issue when converting double into String.
What you are doing is probably using StringBuilder#append(double) which in the end calls Double#toString().
See the javadoc of those methods and find out how double values are converted to String.
Alternatively, if you want to have control over your code, use NumberFormat or it's subclasses.
Related
I'm working with HBase on a project and running into a seemingly simple situation that is throwing me for a loop. Hbase can store table values as escaped hexadecimal. In my case, I have true/false being stored as \x00 and \xFF, respectively.
The problem is (besides being unfamiliar with Java) I need to find a way to convert these to bool, or at least to compare them in a like-bool situation. They will never be anything other than \x00 and \xFF.
Is there not an elegant way to do this?
Please help, I'm really stuck.
Edit: This is probably relevant Hbase shell - how to write byte value
I suspect you could do something like... Hex ->binary->boolean.
But there might even be a toBoolean method already.
Or you could override the compare method they're using. But this could yield undesirable effects.
Can you post the API for the class you're using?
Ok, apparently there is a Bytes.toBoolean() function.
I have a .toUpperCase() happening in a tight loop and have profiled and shown it is impacting application performance. Annoying thing is it's being called on strings already in capital letters. I'm considering just dropping the call to .toUpperCase() but this makes my code less safe for future use.
This level of Java performance optimization is past my experience thus far. Is there any way to do a pre-compilation, set an annotation, etc. to skip the call to toUpperCase on already upper case strings?
What you need to do if you can is call .toUpperCase() on the string once, and store it so that when you go through the loop you won't have to do it each time.
I don't believe there is a pre-compilation situation - you can't know in advance what data the code will be handling. If anyone can correct me on this, it's be pretty awesome.
If you post some example code, I'd be able to help a lot more - it really depends on what kind of access you have to the data before you get to the loop. If your loop is actually doing the data access (e.g., reading from a file) and you don't have control over where those files come from, your hands are a lot more tied than if the data is hardcoded.
Any many cases there's an easy answer, but in some, there's not much you can do.
You can try equalsIgnoreCase, too. It doesn't make a new string.
No you cannot do this using an annotation or pre-compilation because your input is given during the runtime and the annotation and pre-compilation are compile time constructions.
If you would have known the input in advance then you could simply convert it to uppercase before running the application, i.e. before you compile your application.
Note that there are many ways to optimize string handling but without more information we cannot give you any tailor made solution.
You can write a simple function isUpperCase(String) and call it before calling toUpperCase():
if (!isUpperCase(s)) {
s = s.toUpperCase()
}
It might be not significantly faster but at least this way less garbage will be created. If a majority of the strings in your input are already upper case this is very valid optimization.
isUpperCase function will look roughly like this:
boolean isUpperCase(String s) {
for (int i = 0; i < s.length; i++) {
if (Character.isLowerCase(s.charAt(i)) {
return false;
}
}
return true;
}
you need to do an if statement that conditions those letters out of it. the ideas good just have a condition. Then work with ascii codes so convert it using (int) then find the ascii numbers for uppercase which i have no idea what it is, and then continue saying if ascii whatever is true then ignore this section or if its for specific letters in a line then ignore it for charAt(i)
sorry its a rough explanation
I am currently trying to perform some regex on the result of a DatagramPacket.getData() call.
Implemented as String myString = new String(thepkt.getData()):
But weirdly, java is dropping the end quotation that it uses to encapsulate all data(see linked image below).
When I click the field in the variable inspector during a debug session and don't change anything, when I click off the variable field it corrects itself again without me changing anything. It even highlights the variable inspection field in yellow to signal change.
Its values are also displaying like it is still a byte array rather than a String object
http://i.imgur.com/8ZItsZI.png
It's throwing off my regex and I can't see anything that would cause it. It's a client server simulation and on the client side, the getData returns the data no problem.
I got it working by using the solution provided in:
https://stackoverflow.com/a/8557165/1700855
But I still don't understand how not specifying the length of the packet to the String constructor would cause it to drop the systematic end double quotes. Can anyone provide an explanation as I really like to understand solutions to my issues before moving on :)
The problem is that you didn't read the spec for DatagramPacket.getData:
Returns the data buffer. The data received or the data to be sent
starts from the offset in the buffer, and runs for length long.
So, to be correct, you should use
new String(thepkt.getData(), thepkt.getOffset(), thepht.getLength())
Or, to not use the default charset:
new String(thepkt.getData(), thepkt.getOffset(), thepht.getLength(), someCharset)
When computing 2 doubles, 1/81 on the android platform, 0.01234567* was returned. What does the asterisk mean and how can I avoid such an output?
a=Double.parseDouble(subexp.substring(ss, i));
b=Double.parseDouble(subexp.substring(i+1, se+1));
subexp=subexp.substring(0,ss).concat(Double.toString(a/b))
.concat(subexp.substring(se+1,subexp.length()));
so basically the piece of offending code is above, with the following values grabbed from the debugger:
subexp="1+1/81" (before code)
"1+0.01234567*" (after code)
ss=2, se=5, i=3, a=1.0, b=81.0
Not to be a smartass, but if you just don't want the asterisk, try this immediately before you output your string:
subexp = subexp.replaceAll("\\*", "");
If your result requires something more elaborate than this, please provide more information and/or more complete source code, and I'll try to adapt my answer.
I made a simple project to test your code as posted. I printed the string out in the console as well as putting it in a TextView. In both places I get "1+0.012345689012345678", so I can't seem to replicate your results with the asterisk. Perhaps the problem is somewhere else in your code.
Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.
But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.
Is there a way to say to Eclipse "Don't touch this block of text! I have formatted it just the way I like, and you would make it just less readable"?
I assume you do not really mean ‘Clean Up’, but the ‘Format source code’ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called ‘On/Off Tags’. Sadly, it’s off by default. You would now write it like so:
// #formatter:off
StringBuilder sql = new StringBuilder()
.append("SELECT whatever \n")
.append("FROM some_table");
// #formatter:on
It may well be possible that the accepted answer was correct at the time of writing, however, this was introduced in Eclipse 3.5, if I’m not mistaken.
I have experienced the same problem, and while I don't have a solution, I can tell you how I work around the problem.
Because of how formatting works, I deliberately avoid lines of code that are excessively long. In general, when I keep lines short, it makes better decisions as to how to format the code. This can even work with SQL statements, for example:
public static final String SELECT_SOMETHING = "SELECT"
+ "OBJECTID, THIS, THAT, THEOTHER, THING"
+ " FROM DBNAME.DBSCHEMA.TABLE_T"
+ " WHERE ID = ?";
This statement formats reasonably, because where possible items were split apart and concatenated together. When I don't do this, I get unpredictable results:
public static final String SELECT_SOMETHING = "SELECT OBJECTID, SOMETHING FROM DBNAME.DBSCHEMA.TABLE_T WHERE ID = ?";
For comments, I place them all on a single line when possible, and allow it to word wrap when it does the formatting.
Also, it is possible to change the style using the code formatter to make things work better for your coding style. You may want everyone on the team to use the same format, just to avoid conflicts. Because it is easier to compare changes with other developers, or prior versions using your source control tool, even if it makes parts of your code less readable, using the formatter has still been to my advantage.
Still, I understand your frustration when the formatter makes bad decisions!
Feeling iffy about replying to my own question, but there's a workaround I currently do (note: I have these cleanup rules as a save-action):
Save (with Ctrl/Cmd-S, don't know if it matters how you save) the code, and let Eclipse mess up your formatting. Then just press Ctrl/Cmd-Z to undo, and immediately re-save. The format reverts back to its original format and seems to be saved as intended.
For SQL statements in code, you can put a single-line comment character at the end of each line. Then the formatter can't reformat it. It's uglier than not having to do it, but it's prettier than if Eclipse formats it.
StringBuffer sql = new StringBuffer() //
.append("SELECT whatever \n") //
.append("FROM some_table");
No. (To the best of my knowledge, and I have had the same problem and have looked many times hard and long...)
(for Javadoc comments only)
If I have a block of text that formatted just the way I like, I enclose them by the <pre></pre> tags.
if you don't want a field to become final (i.i: because you want to change it while debugging), you just assign it to itself on the constructor. This would get an eclipse warning, but your field will stay non-final.