Getting Specific symbols to appear using getCurrencyInstance() in Java - java

I'm writing a very simple and small example class to try and show how the .getCurrencyInstance() of the NumberFormat class in Java works, but my output is looking a little funky. It seems the class is working, but when it tries to print out the actual symbols for currency (like the Japanese yen symbol or the British pound symbol) I get weird symbols instead. Is there any way to fix this? Is there something I need to import to get these symbols on my computer?
Here's my code:
import java.util.*;
import java.text.*;
public class CurrencyFormatExample
{
public static void main(String[] args)
{
double convert = 9398.9398;
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
System.out.println("American: " + currencyFormat.format(convert));
Locale swedish = new Locale("sv", "SE");
NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish);
System.out.println("Swedish: " + swedishFormat.format(convert));
Locale japanese = new Locale("ja", "JP");
NumberFormat japaneseFormat = NumberFormat.getCurrencyInstance(japanese);
System.out.println("Japanese: " + japaneseFormat.format(convert));
Locale russian = new Locale("ru", "RU");
NumberFormat russianFormat = NumberFormat.getCurrencyInstance(russian);
System.out.println("Russian: " + russianFormat.format(convert));
Locale british = new Locale("en", "GB");
NumberFormat britishFormat = NumberFormat.getCurrencyInstance(british);
System.out.println("British: " + britishFormat.format(convert));
}
}
Here is the output I get with this:
American: $9,398.94
Swedish: 9á398,94 kr
Japanese: ?9,399
Russian: 9á398,94 ???.
British: ú9,398.94
As you can see that's clearly not right. Any way I can remedy this?

In jGRASP: "Settings" > "Font", "Charset" tab. Change "I/O Charset" to UTF-8. In the "Compiler" tab, "Flags / Args" sub-tab, for "FLAGS2" of the "Run" command, add "-Dfile.encoding=UTF-8".
The "file.encoding" change will also change the default encoding files that your program reads and writes. Unfortunately, Java does not provide a way to specify a different charset for normal file I/O and I/O from stdin, stdout, and stderr when they are connected to pipes rather than a console (most IDEs will use pipes). So if you want native encoding to be used by default within your program and still want UTF-8 for I/O to the IDE, there is no way to do it. Thus, it would not be wise for the IDE to automatically add the "file.encoding" flag, unless there is a "Just use UTF-8 for everything" setting.

If you're executing this code in Eclipse, adjust your Window > Preferences > General > Workspace text encoding to UTF-8

Related

Inserting line break after method name in Java method declaration

public MyClass aVeryLongMethod(
String args1, String args2, String args3, String args4, String args2)
throws Exception
{
myMethod();
I have an eclipse style java formatter (on VSCode). What are the indentation settings for the following?
line break after the method name aVeryLongMethod(
Double indent for hanging lines in method declaration (8 spaces before args1)
There is no specified line indentation in Java. That means unline Python, in Java indentations are not syntactically counted. White spaces are ignored by the lexer.
Anyway, it is important to have a better indentation for clean code. You can use the VS Code formatted to format your indentations. If I have such a case, I used to the following syle.
public MyClass aVeryLongMethod(
String args1,
String args2,
String args3,
String args4,
String args2
) throws Exception {
myMethod();
}
On Eclipse, the java formatter can be configured as follows (Java -> Code style -> Formatter -> edit Active Profile). The line width affects the final result I guess. Profile can be exported also.
Open Command Palette, there's Java: Open Java Formatter Settings with Preview, where you can customize your formatting style. Turn to the option Wrapping, you can set the code max length.
In my following example, the length to the end of function name is 32, so if i set the max length as 32, turn back to .java file, right click and choose Format Document, please see the effect:
Have a try.

How to make a symbol appear in Netbeans output for Maven project?

I have tried all kinds things but nothing is working.
Netbeans is always displaying a " ? " instead of the symbol itself ♤ ♡ ♢ ♧
My project is encoded UTF-8.
I changed to font for the Output window to Segoe UI Symbol.
It's still printing < ? >
My code:
You probably just need to specify a font for the Output window that can render the characters "♤ ♡ ♢ ♧". One such font is Segoe UI Symbol, and to set that as the font in the Output window:
Tools > Options > Miscellaneous > click the Output tab > Font
Set the font to Segoe UI Symbol and click OK.
Then just run your application again, and the characters will be rendered correctly in the Output window:
If that doesn't resolve your problem, please update your question to show your code.
Updated on 1/5/20, based on OP feedback:
Changing the font did not help, and with hindsight this was not necessary anyway.
The issue relates only to Maven projects in NetBeans. Ant projects don't have this problem.
To render the playing card symbols in the Output window:
In the NetBeans configuration file etc/netbeans.conf, append -J-Dfile.encoding=UTF-8 to the end of the property value for netbeans_default_options (just before the closing quote).
Save the change and then restart NetBeans.
The PrintStream used by System.out must support UTF-8. This can be achieved in two different ways:
Open the project's properties, and set -Dfile.encoding=utf-8 for Properties > Run > VM Options so that the default PrintStream uses UTF-8 encoding at run time.
Alternatively, in the code create and use a UTF-8 PrintStream instead. See the code below for the details.
Here's the code:
package com.unthreading.emojimaven;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
public class App {
public static void main(String[] args) throws UnsupportedEncodingException {
String symbPique = "\u2660";
String symbCoeur = "\u2665";
String symbCarreau = "\u2666";
String symbTrefle = "\u2663";
System.out.println("System.getProperty(\"file.encoding\")=" + System.getProperty("file.encoding"));
System.out.println("StandardCharsets.UTF_8.name(): " + StandardCharsets.UTF_8.name());
System.out.println("Charset.defaultCharSet()=" + Charset.defaultCharset());
System.out.println("Default PrintStream: " + symbCarreau + "--" + symbCoeur + "--" + symbPique + "--" + symbTrefle);
PrintStream outStream = new PrintStream(System.out, true, StandardCharsets.UTF_8.name());
outStream.println("UTF-8 PrintStream: " + symbCarreau + "--" + symbCoeur + "--" + symbPique + "--" + symbTrefle);
}
}
Here's the output when project's VM Options is set to -Dfile.encoding=utf-8:
------------------------------------------------------------------------
Building emojimaven 1.0-SNAPSHOT
------------------------------------------------------------------------
--- exec-maven-plugin:1.5.0:exec (default-cli) # emojimaven ---
System.getProperty("file.encoding")=UTF-8
StandardCharsets.UTF_8.name(): UTF-8
Charset.defaultCharSet()=UTF-8
Default PrintStream: ♦--♥--♠--♣
UTF-8 PrintStream: ♦--♥--♠--♣
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 0.717 s
Finished at: 2020-01-05T00:21:16-05:00
Final Memory: 7M/60M
------------------------------------------------------------------------
Notes:
The change to netbeans.conf is essential, so that NetBeans configures the Output window for UTF-8 during startup.
The default font for the Output window is Monospaced. Since that renders the playing card symbols correctly there is no need to change it, at least for the requirement given in the OP.
There is no need for any special settings in pom.xml.

Java - Error message showing question marks instead of characters

$ javac Increment.java
Output:
Increment.java:6: ??: ?????
System.out.println(++a++);
^
??: ??
??: ?
1 ???
here is the code
class Increment{
public static void main(String[] args) {
int a = 5;
System.out.println(++a++);
}
}
Does any one know what may be happening and how to fix it?
Increment is just a class for testing so that a error will appear.
I am running it in git-bash terminal, but I have tried it in cygwin terminal and windows's terminal as well.
character-set is UTF-8.
Most probably you have a national locale set up (e.g. Russian, Chinese or anything else) that makes the Java compiler to return nationalized error messages, but your terminal (cygwin) does not support the UTF-8 output or your system does not support UTF-8 locale.
As the quickest work-around you could switch java compiler to provide error messages in English:
$ javac -J-Duser.language=en Increment.java

Sublime Text cannot recognize NumberFormat

I have the following simple code in a (Windows 10) sublime text 3 file NumberFormat.java, to format a double to US currency:
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
public class NumberFormat {
public static void main(String[] args) {
double num = 1000.322;
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
System.out.println("US: " + defaultFormat.format(num));
return;
}
}
When I build, however, the follow errors show up exclusively for NumberFormat.
NumberFormat.java:2: error: NumberFormat is already defined in this compilation unit
import java.text.NumberFormat;
^
NumberFormat.java:10: error: cannot find symbol
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
^
symbol: method getCurrencyInstance()
location: class NumberFormat
NumberFormat.java:11: error: cannot find symbol
System.out.println("US: " + defaultFormat.format(num));
^
symbol: method format(double)
location: variable defaultFormat of type NumberFormat
3 errors
As far as I can see, there are no errors with the code. In addition, this code snippet outputs US: $1000.32 as it should on all other IDEs and text editors. Can someone explain what these errors mean? And why they exclusively occur with sublime text?
The problem is that you have imported a class called NumberFormat into a class with the same name. This is resulting in confusion over which class NumberFormat actually refers to.
(The confusion is in your mind actually. The Java language spec is clear about it. It says that NumberFormat will refer exclusively to your class. The import has not effect. Any compliant Java compiler will make the same interpretation.)
There are two solutions:
Don't import the class. Instead refer to it using its fully qualified name.
Change the name of your class so that it doesn't collide with the class you are importing.
To my mind, the second solution is better. Especially since NumberFormat is not a good name for your class anyway.
And why they exclusively occur with sublime text?
They don't. The code you have written won't compile with any conformant Java compiler.
I think you should modify your class name to a class that is different from the imported class name,or you can change you source to
java.text.NumberFormat defaultFormat = java.text.NumberFormat.getCurrencyInstance();
This is not an issue of Sublime. Sublime simply invokes the javac command from your path. You get the same result if you compile using javac outside the sublime
changing class name or be part of an explicit package name solves the problem
The
import java.text.NumberFormat
conflicts with a type defined in the same file. Changing your class name would resolve the problem.

Missing currency symbols on linux server

I have a java application that needs to display currency symbols. I'm running on a Linux(Ubuntu) server.
On Linux server LANG=en_GB.UTF-8
The following code tests the problem:
import java.util.Currency;
import java.util.Locale;
import java.text.NumberFormat;
public class SymbolTest
{
public static void main(String[] args)
{
System.out.println("Hardcoded Unicode Currency Symbol for GBP [\u00A3] ");
System.out.println("Currency Symbol for GBP with Locale [" + Currency.getInstance(Locale.UK).getSymbol() + "]");
System.out.println("Currency Symbol for US with Locale [" + Currency.getInstance(Locale.US).getSymbol() + "]");
System.out.println("Currency Symbol for FRANCE with Locale [" + Currency.getInstance(Locale.FRANCE).getSymbol() + "]");
}
}
gives the output:
Hardcoded Unicode Currency Symbol for GBP £
Currency Symbol for GBP with Locale [£]
Currency Symbol for US with Locale [USD]
Currency Symbol for FRANCE with Locale [â¬]
I suspect this is a Locale or Lang problem on the Ubuntu server.
What should I install/configure on the linux server to enable the currency symbols to display?
Your program is correctly trying to output UTF-8, but your terminal apparently doesn't know that it's supposed to be in UTF-8 mode. So your terminal is at fault here. What terminal are you using?
Try redirecting the output of the program to a file and open that file with a UTF-8 capable editor to verify that the output is correct.
I'm guessing that the issue is probably related to the way you're actually formatting the number or locale rather than the font. Check out the Grails reference on formatting numbers as currency and the java.util.Currency API doc for more information. A quick way to rule out a font related issue is just to type (copy&paste if necessary) the symbol you're after into a GSP and verify that you can view it in your browser:
₣
$
₤

Categories

Resources