im trying to format this string into a fixed column style but cant get it to work, heres my code, whats up?
System.out.format("%32s%10n%32s%10n%32s%10n", "Voter: " + e.voteNo + "Candidate: " + vote + "Booth: " + boothId);
All variables are integers,
I want the output to be like
Voter: 1 Candidate: 0 Booth: 1
Thanks
Please stop trying to program by accident. Your code looks like the glued-together parts of 3 different approaches to solving the issue. Try to read the documentation on the topic (JavaDoc is your friend!) and apply what you learned instead.
String result = String.format("Voter: %-10d Candidate: %-10d Booth: %-10d", e.voteNo, vote, boothId);
System.out.println(result);
For more information on String.format check its JavaDoc.
Edit: apparently I didn't get the memo that there's actually a PrintStream.format, so you can actually write it like this:
System.out.format("Voter: %-10d Candidate: %-10d Booth: %-10d", e.voteNo, vote, boothId);
Related
I will split up this problem to be more easy to me :
for this expression :
"created":"589c8377576a33706397f3f4"
I write this regex :
output_row.json.replaceAll("\"created\":\"589c8377576a33706397f3f4\"","");
It works ! Now I would like to use a dynamic token e.g. [[:xdigit:]].
I try this but It didn't work !
output_row.json.replaceAll("\"created\":\"[[:xdigit:]]\"","");
Could you advice me, please ?
[[:xdigit:]] is exactly one hex digit. Add the + quantifier to match 1 to n, or the * to match 0 to n hex digits.
Finally I found the answer :
//replace the value of the key created
output_row.json = output_row.json.replaceAll("\"created\":\"[a-zA-Z0-9]+\"","\"created\":\"" + formatted + "\"");
I don't know why this class is not accepted in Talend editor : [[:xdigit:]]not specific to Java perhaps ?
Anyway the topic is closed for me !
Ale
I'm trying to program a replacement logic for invalid phone numbers, which I provide with a Map
I read through a few Regex expressions threads, but I don't know if this actually is possible.
Example:
Input phone number: +410712345678
regex I'm trying to use:
"^\\+(?:[0-9] ?){6,14}[0-9]$"
number after regex and filtering should be: +41712345678. So actually removing the first Instance of 0.
Second example:
input phone number: +41(071)2345678
regex I'm trying to use:
"^\\+(?:[0-9] ?)\\({0,3}\\){3,11}[0-9]$"
number after regex and filtering should be: +41712345678. So actually removing the First Instance of 0 and also the braces.
I'm trying to user some kind of pattern to automatically remove those invalid pieces from those phone numbers. The numbers need to be formatted that way to work with my VOIP application.
Is there any way to create a filter pattern like that with regex?
Seems like you should only apply that rule for Switzerland phone number, i.e. for +41 numbers, because simply removing the first 0 from any international number is wrong.
So, ph = ph.replaceFirst("^(\\+41)\\(?0?([0-9]{2})\\)?", "$1$2").
See regex101 for how it works.
Thank you for your answer.
I applied the Regex to my TestImport with the following code:
//...
log.debug("Applying Regex :" + SearchString + " with Replace: " + ReplaceString);
log.debug("Applying Regex for Number:" + Person.get(EPerson.Rufnummer));
Person.put(EPerson.Rufnummer, Person.get(EPerson.Rufnummer).replaceFirst(SearchString, ReplaceString));
log.debug("New Number is:" +Person.get(EPerson.Rufnummer));
log.debug("Applying Regex for Number:" + Person.get(EPerson.RufnummerMobil));
Person.put(EPerson.RufnummerMobil, Person.get(EPerson.RufnummerMobil).replaceFirst(SearchString, ReplaceString));
log.debug("New Number is:" +Person.get(EPerson.RufnummerMobil));
//...
DEBUG [AddressbookFactory] Applying Numberfilter to: {Vorname=Testinator, Nachname=Test, Rufnummer=+410717271818, RufnummerMobil=, RufnummerPrivat=+41(071)7271818, Fax=, Strasse=, PLZ=, Stadt=, Bundesland=, Email=, Firma=, URL=}
DEBUG [AddressbookFactory] Regex Detected
DEBUG [AddressbookFactory] Applying Regex :^(+41)(?0?([0-9]{2}))? with Replace: $1$2
DEBUG [AddressbookFactory] Applying Regex for Number:+410717271818
DEBUG [AddressbookFactory] New Number is: +41717271818
DEBUG [AddressbookFactory] Applying Regex for Number:+41(071)7271818
DEBUG [AddressbookFactory] New Number is: +41717271818
...
And it worked!
Thank you so much for your Quick Response!
I marked your answer as useful, but trough my "newbie" Reputation it does not indicate it.
This Question is resolved.
Sincerly Fabian95qw
While working on Sonar static code analyzer I found some confusing (may be only to me) statement by Sonar on using parentheses.
Below are the few code snippets where Sonar says remove useless parentheses:
line>1 String auth = "Basic "+ com.somepackge.someMethod(((String) (parent.proxyUsername+ ":" + parent.proxyPassword)));
line>2 return rawtime.length() > 3 ? (rawtime.substring(0, rawtime.length() - 2) + rawtime.substring(rawtime.length() - 2, rawtime.length()).toLowerCase()) : rawtime;
though I have replaced above lines with below one to keep Sonar calm :) :
Line>3 String auth = "Basic "+ com.somepackge.someMethod((String) (parent.proxyUsername+ ":" + parent.proxyPassword));
Line>4 return rawtime.length() > 3 ? rawtime.substring(0, rawtime.length() - 2) + rawtime.substring(rawtime.length() - 2, rawtime.length()).toLowerCase() : rawtime;
So the reason for discussing this question is:
Actually using braces/parentheses are way to reduce the confusion so why to remove those parentheses.
What is best way to use parentheses while writing any complex statement in java.
See the line>1 and Line>4 here I think
(String) (parent.proxyUsername+ ":" + parent.proxyPassword)
this part of code should have the braces to avoid confusions but what Sonar expect is something like:
(String) parent.proxyUsername+ ":" + parent.proxyPassword
Any suggestion would be a great help. I got some links regarding this question but those were not much helpful.
First snippet
String auth = "Basic "+ someMethod(((String) (parent.proxyUsername+ ":" + parent.proxyPassword)));
You could rewrite it as:
String auth = "Basic "+ someMethod(parent.proxyUsername+ ":" + parent.proxyPassword);
because the string concatenation operator already does a string conversion. Unless you want a ClassCastException thrown when proxyUsername or proxyPassword are not Strings?
Second snippet
return rawtime.length() > 3 ? (rawtime.substring(0, rawtime.length() - 2) + rawtime.substring(rawtime.length() - 2, rawtime.length()).toLowerCase()) : rawtime;
The parenthesis is indeed unnecessary but the statement is quite unreadable. If you want to keep using the ternary operator I would suggest splitting the statement across lines:
return rawtime.length() > 3
? rawtime.substring(0, rawtime.length() - 2) + rawtime.substring(rawtime.length() - 2, rawtime.length()).toLowerCase()
: rawtime;
or you could revert the condition:
return rawtime.length() <= 3 ? rawtime :
rawtime.substring(0, rawtime.length() - 2) + rawtime.substring(rawtime.length() - 2, rawtime.length()).toLowerCase();
Line 1 has redundant parentheses, but Line 2's parentheses add clarity to the ternary statement.
Whether or not the extra parenthesis in 2 are useful is up for debate - but there's no reason not to remove the redundant ones in 1.
Generally it's best to use extra parenthesis to convey your intent about what the code should do, or to remove ambiguity in the order that things occur.
There is a semantic difference between these two versions:
(String) (parent.proxyUsername+ ":" + parent.proxyPassword)
(String) parent.proxyUsername+ ":" + parent.proxyPassword
In the first, the second set of () already evaluates to a String, implicitly calling parent.proxyUsername.toString() to convert proxyUsername to a String. So the cast is redundant and should be removed IMHO. The second version casts parent.proxyUsername to String, and will throw an exception is it hasn’t got runtime type String (only if it is declared a String is the cast redundant).
I agree that line 2 and 4 are complicated to read no matter if they have the redundant braces or not. Rewrite if you want clarity. That said, redundant braces are sometimes good for clarity IMHO, I do use them occasionally.
the best way is to put your class that you're casting to in a parentheses then the whole part to be converted in another parentheses, then include this whole code in a container parentheses, your code should look like this e.g ((String)(x+y)).
I hope that was helpful, thanks.
I have a JSON String like the following:
json = "{\"Things\": \n" +
" {\"Thing\": {\n" +
" \"ID\":\"123\",\n" +
" \"name\":\"Yet Another Thing\",\n" +
" \"price\":\"$12.99\",\n" }\n" +
" }\n" +
"}";
Is there a way I can assert that the ID of Thing is 123 AND that it's name is "Yet Another Thing" in the same statement/assert?
At the moment, I seem to fail using filters:
JsonPath.read(json, "$.Things.Thing[?(#.ID == '123')].name")
I get the following exception:
java.lang.IllegalArgumentException: Invalid container object
Is that maybe because thereis no array notation [] in the JSON string above? Should there be?
On a related note, is there a good introduction to using Hamcrest (with JSON assert)? I know the official tutorial, but I always seem to get it wrong...
UPDATE: The rational for this was: what if I get several Thing elements back, about whose order I have no guarantee (so I can't match Thing[1] (unless I looped through them all))? How do I make sure one element has both, the right ID and the right name? If I check for the children separately, don't I run the risk that one Thing has the right name and another the right ID, but none has both? (Would that be possible with that JSON format, or would I have to an array in that case anyway, like "Thing": [ { ... }, { ... } ], ... ?
P.S.: I tried to use the JsonPath above as follows in the end: assertEquals("Yet Another Thing", JsonPath.read(json, "$.Things.Thing[?(#.ID == '123')].name"));
So that's where the exception might have come from, too. Also, I initially asked this question on the JsonPath mailing list, but didn't get any replies so far, so was hoping I might get help here quicker... :)
The tutorial gives the solution to your problem, it seems:
JsonAssert.with(json).assertThat("$.Things.Thing.ID", Matchers.equalTo("123"))
.assertThat("$.Things.Thing.name", Matchers.equalTo("Yet Another Thing"));
I got a question about printf in a program, in the end i wrote:
System.out.print(area[i]+" ");
It prints:
2.000000000000001 12.0 28.274333882308138
Then I tried to use printf to replace it:
System.out.printf("%4.1f",area[i]+" ");
However, it has errors when it was executed:
f != java.lang.String
I know probably it is because 4.1 is wrong configuration for the value of 2.000000000000001, as there wont be 4 digits wide if I only retrieve 1 digit after the dot, but what does the error message mean?
Due to the concatenation operator +; area[i] + " " is a java.lang.String type. The error on execution is telling you this.
Error messages are your friends. Do learn to appreciate them.
The error may comme from the fact that in your expression :
System.out.printf("%4.1f",area[i]+" ");
You don't print a float, but a String (yes, area[i]+" " is a String).
Try with :
System.out.printf("%4.1f",area[i]);
It should go better, doesn't it ?