How can I assign the Euro or the Pound symbol to a variable?
I need to assign 开发者_开发百科the Euro or the Pound symbol to a variable. How can i do this?
String euro = "";// What i have to write here??
System.out.println(euro);// I need to print euro symbol
public class ExampleEuroPound {
public static void main(String args[]){
String euro = "\u20ac";
String pound = "\u00a3";
System.out.println("pound = " + pound);
System.out.println("euro = " + euro);
}
}
If you can't type it then you could use the unicode value for euro:
String euro = "\u20AC";
System.out.println(euro);
If you're doing this however, best practice is to comment it and / or save it as a constant field for clarity (unexplained unicode literals in code are just plain confusing!):
public static final String POUND = "\u00A3";
public static final String EURO = "\u20AC";
public final static char EURO = '\u20ac';
I'd wonder if you'd be better off using the currency formatter for numbers in the java.text
package. IF there's ever a chance that you'd want to use something other than euro, based on locale, this would be a better choice.
You might also think about a Money class. I think you need a better abstraction than mere Strings or doubles for programs that involve cash.
There are two ways:
- Type or copy/paste the Euro/Pound symbol into your source code. This requires the editor/IDE to support these characters (typically not a problem) and to use an encoding that does (potentially a problem), and for the compiler to use the same encoding (potentially a problem). Overall, this is risky since it can break whenever something in the development or build environment changes.
- Use a unicode escape sequence in the source code:
\u20AC
is the Euro sign,\u00A3
the Pound sign.
What would be the point of doing
String euro = "€";
http://download.oracle.com/javase/6/docs/api/java/util/Currency.html#getInstance%28java.lang.String%29
You should do it like this:
String euro = "\u20AC";
A full list of Unicode currency symbols is available as a pdf here.
精彩评论