Problem using Currency class/methods
Hi everyone,
I am new to Java and am trying to teach myself using any online resource I can. I have 2 questions
1) Can anyone tell me whats wrong with this piece of code. It compiles OK but when I run I get
Illegal.Argument.Exception at Java.util.Currency.getInstance(Currency.java:242)
Heres the code (trying to retrieve the ?symbol into a string symbol)
Currency myCurrency = Currency.getInstance(new Locale("UK"));
String symbol;
symbol = myCurrency.getSymbol();
2) I'm looking for an online resource of Java exercises which I can use to test my knowledge. Does anyone know of a good one?
1.) Please use copy-and-paste for error messages. and don't capitalize the "java" in "java.util.Currency"
2.) Currency is probably complaining because your Locale object is invalid. The first parameter of Locale is the language, and "UK" is not a valid language. You might want to try "new Language("en", "UK")" or simply use Locale.UK
1) doc says it throws IllegalArgumentException if the country of the given locale is not a supported [url= http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html]ISO 3166[/url] country code.I guess you should use "GB" instead of "UK", or Locale.UK (which country is in fact
> 1) doc says it throws IllegalArgumentException if the
> country of the given locale is not a supported
> [url=http://userpage.chemie.fu-berlin.de/diverse/doc/I
> SO_3166.html]ISO 3166[/url] country code.
> I guess you should use "GB" instead of "UK", or
> Locale.UK (which country is in fact "GB".)
Indeed. My advice was only half-correct. Locale.UK should work, "new Locale("en", "UK")" will not, because it should be "new Locale("en", "GB")" instead.
OK guys. Thanks for the advice. I have fixed the problem with the locale but am still getting errors with the Currency class. I can't instantiate it. My code now looks like this.
Locale england = new Locale("en","UK");
System.out.println(england.getDisplayName());
Locale.setDefault(england);
Currency myCurrency;
myCurrency = Currency.getInstance(england);
String symbol;
symbol = myCurrency.getSymbol();
System.out.println(symbol);
It compiles OK but when I run it I get this output
English (UK)
Exception in thread "main" java.lang.IllegalArgumentException
at java.util.Currency.getInstance(Currency.java:258)
I can't get to grips with this single instance only of the Currency class. The API says
The class is designed so that there's never more than one Currency instance for any given currency. Therefore, there's no public constructor. You obtain a Currency instance using the getInstance methods.
Worked it out. When I specified my Locale it should have been
Locale england = new Locale("en","GB");
not
Locale england = new Locale("en","UK");
I think UK can be either euro or GBP for some odd reason.
Thanks for your help.
Does anyone know of any good resources for java exercises by the way?