java.util.UnknownFormatConversionException: - java

System.out.printf("%s%13s%\n", "TarrifType", "AnnualCost");
System.out.printf("%s%d.%n", "String" 243.08);
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '
at java.util.Formatter.checkText(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at ModelComparison.main(ModelComparison.java:12)
Any idea whats wrong?

What's wrong is the %\n in the first line. Note that the % is a special character in a format string that indicates that a format specifier follows. The \n after the % is not a valid format specifier.
If you wanted to print a percent sign, then double it in the format string: %%
If you wanted to print a newline, then use %n, not %\n.

The problem in your format string is that you mixed two ways of doing newline: %n and \n. The former tells the formatter to put a newline in whatever format the platform requires, whereas the latter puts in just a literal newline char. But what you wrote was %\n, which means you're escaping the newline char, and that's what's blowing up.
You also forgot a comma between "String" and 243.08 in the second call. And btw, %d formats an integer, so you probably don't want it if you're trying to print 243.08.

Bugs..
System.out.printf("%s%13s\n", "TarrifType", "AnnualCost");
System.out.printf("%s%f\n", "String", 243.08);
http://ideone.com/USOx1

In my case (Android) there was an error in strings.xml:
<string name="cashback">10% cashback</string>
When I tried to get getString(R.string.cashback), I received this exception. To fix it, replace % with %%.

If a string desired to format in Kotlin, the following code snippet can be used.
In the string.xml:
<string name = "exampleString"><![CDATA[<font color=#3177a3> String_1: <b>%%s</b><br> String_2: <b>%%s</b><br> String_3: <b>%%s</b></font>]]></string>
In the main code:
val format = String.format(getString(R.string.exampleString),
value1,
value2,
value3
)

Related

Cannot parse "1,000.00" String to Number

I have several labels displaying numeric values and I need to parse these texts to number. The problem is that when the value is greater than 999, the parse method fails throwing the following exception:
Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string: "1,000.00" at
java.lang.NumberFormatException.forInputString(Unknown Source)
I tried several parse methods like Double.valueOf(string), new BigDecimal(string), new BigInteger(string) and so on...but the exception is always thrown.
I guess you are using a French numbers.
You can add a Locale to NumberFormat and parse in the documentation :
NumberFormat.getNumberInstance(Locale.FRANCE).parse("1,000")
Remove the comma before parsing like this:
double d = Double.parseDouble(string.replace(",", ""));

Replace backslash in string

I have a String in which I am trying to replace the number enclosed by two backslashes. For example: \10\ , I am trying to replace that with 10. I am currently using this regex to do that:
String texter = texthb.replaceAll("\\.+\\", "\\"+String.valueOf(pertotal + initper)+"\\");
This line is giving the following error:
Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 4
.+\
I know it is because the regex is wrong. What is the proper way to accomplish this? Thanks in advance.
Use four backslashes to match a single backslash character.
String texter = texthb.replaceAll("\\\\.+?\\\\", "\\\\"+String.valueOf(pertotal + initper)+"\\\\");

Look-behind group for a Java regular expression does not have an obvious maximum length near

I want to:
When I get a big string I need to find stuff in it using a regular expression in Java to separate using the following formulas:
If a line (after \n) has over 1000 characters, check if the 1000th character is enclosed in after an odd '.
Then add a concat string '\n||' between the 1000 and 1001 characters
If 1000 and 1001 characters are '' (escape character for plsql) then insert it between 1001 and 1002
Anyway I made this regular expression:
"\n(?<kiloCharacters>[^\n]{1000})(?<=(?<newLine>\n)(?<pairsAndText>[^'\n]{0,1001}|[^\n']{0,1001}'[^\n']{0,1001}'[^\n']{0,1001}){0,1001}(?<oddComa>')(?<text>[^\n']{0,1001}))(?(?<=')(?!'))"
Let me explain it:
"\n(?<kiloCharacters>[^\n]{1000}) --> Newline and 1000 characters
(?<= --> Let's look behind to check if we have an odd number of '
(?<newLine>\n) --> Start from new line
(?<pairsAndText> --> All pairs of '
[^'\n]{0,1001} --> Eighter 0 '
| --> or
[^\n']{0,1001}'[^\n']{0,1001}'[^\n']{0,1001}){0,1001} --> (text* ' text* ' text* )*
(?<oddComa>') --> Last comma
(?<text>[^\n']{0,1001}) --> Text after that comma
) --> End of actual looking behind
(?(?<=')(?!'))" --> This part check if we are inside an escaped character '' as we can not concat stuff between here
Anyway, it seems I get the folowing error.
Exception in thread "main" java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 161
(?<kiloCharacters>[^
]{1000})(?<=(?<newLine>
)(?<pairsAndText>[^'
]{0,1001}|[^
']{0,1001}'[^
']{0,1001}'[^
']{0,1001}){0,1001}(?<oddComa>')(?<text>[^
']{0,1001}))(?(?<=')(?!'))
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.group0(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
Why does it do that? Did I not make the limitation by using {0,1001} instead of *?
Java's regex engine does not support variable length look behind. That means that when the length of the look behind is not fixed the engine will throw this exception. Your look behind's length is variable, thus you get this exception.
Java regex error - Look-behind group does not have an obvious maximum length

special character in JSON \n and double quote

I am having problem when convert string to json object.
\n gives out Unterminated string . If I want to use new line I use \n character, then it occurs the error. Example String: Hello \n this is testing message.
double quote " gives out Expected a ',' or '} Exception. Example String : This is a "TESTING" message.
I use to escape \ to escape those , but still facing the JSON Exception
The \n, intended as "newline", must be encoded as \n in json.
\" is for quoting.
You can open the python shell, write
>>> import json
>>> json.dumps('\n"')
and see the result yourself
I use the StringEscapeUtils.escapeJavaScript() function which make my life easy.
http://commons.apache.org/lang/api/org/apache/commons/lang3/StringEscapeUtils.html

Velocity - Correct Regex to remove control characters?

I'm trying to remove undesirable characters from a string in Velocity (newlines are ok, but not things like EM and CAN ASCII control characters).
#set($cleanScreen = $cleanScreen.replaceAll("\p{Cc}", ""))
Throws:
org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 13, column 82. Encountered: "p" (112), after : "\"\\"
at org.apache.velocity.Template.process(Template.java:137)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:415)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1077)
at org.apache.velocity.runtime.RuntimeSingleton.getTemplate(RuntimeSingleton.java:303)
at org.apache.velocity.app.Velocity.getTemplate(Velocity.java:503)
and
#set($cleanScreen = $cleanScreen.replaceAll("[[:cntrl:]]", ""))
This one doesn't thrown an exception, instead, it matches the characters c,n,t,r,l and removes them from the string.
and...
#set($cleanScreen = $cleanScreen.replaceAll("\\p{Cntrl}", ""))
Throws:
java.util.regex.PatternSyntaxException: Illegal repetition near index 2
\\p{Cntrl}
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.closure(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at sun.reflect.GeneratedMethodAccessor168.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.invoke(UberspectImpl.java:295)
at org.apache.velocity.runtime.parser.node.ASTMethod.execute(ASTMethod.java:245)
I've tried several regex's (many seem to work in Java, but not VTL)? My key issue seems to be how things differ in their escaping between Java and Velocity?
Can anyone help? I only have access the the VTL, not the Java class.
I can't comment on the actual regexp.
On the velocity side however, I find that...
#set($cleanScreen = $cleanScreen.replaceAll("\p{Cc}", ""))
#set($cleanScreen = $cleanScreen.replaceAll("[[:cntrl:]]", ""))
...these two are correct as they are. I have a little vtl shell into which I just copy pasted your vtl code. Are you really getting these errors with the first two expressions? How about using '\p{Cc}'?
#set($cleanScreen = $cleanScreen.replaceAll("\\p{Cntrl}", ""))
The '\\p' gets you into trouble.
On a side note, you can use http://velocity.apache.org/tools/devel/generic/EscapeTool.html for all your escaping needs.
Those Velocity Parser Exceptions, might come from the double-quotes characters.
I had similar problem in VTL when trying to String.replaceAll regular expression with a capturing group, like so:
#set( $Jira_links = $Jira_tickets.replaceAll("(CT-\d+)", "http://jira.site.com/browse/$1") )
Throws:
org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 2, column 58. Encountered: "d" (100), after : "\" (CT-\"
Changing it into single quotes worked:
#set( $Jira_links = $Jira_tickets.replaceAll('(CT-\d+)', 'http://jira.site.com/browse/$1') )

Categories