Java Scanner useLocale() Method
Example
Read numbers from a different locale:
// Create a scanner object
Scanner myObj = new Scanner("1.500.000");
// Change delimiter
myObj.useLocale(new Locale("es"));
// Read and display the number
System.out.println(myObj.nextInt());
Definition and Usage
The useLocale() method changes the locale used by the scanner. The locale determines how numbers are interpreted by deciding how digits are grouped, which character serves as a decimal point, etc.
Locale objects
The useLocale() method requires a Locale object as an argument. Locale objects represent a language or country and they are used by a variety of Java classes to handle formatting and interpreting data.
The easiest way to get a Locale object is by using one of the objects provided by attributes of the Locale class.
myObj.useLocale(Locale.GERMANY));
A list of available language and country attributes is shown below.
| Countries | Languages |
|---|---|
Locale.CANADALocale.CANADA_FRENCHLocale.CHINALocale.FRANCELocale.GERMANYLocale.ITALYLocale.JAPANLocale.KOREALocale.PRCLocale.TAIWANLocale.UKLocale.US
|
Locale.CHINESELocale.ENGLISHLocale.FRENCHLocale.GERMANLocale.ITALIANLocale.JAPANESELocale.KOREANLocale.SIMPLIFIED_CHINESELocale.TRADITIONAL_CHINESE
|
If the country or language you need is not in the list then you can create a new Locale object using a language code and an optional country code. Most codes are two or three characters long and each code represents a language or a country.
Locale spanish = new Locale("es");
Locale spain = new Locale("es", "ES");
Syntax
public Scanner useLocale(Locale locale)
Parameter Values
| Parameter | Description |
|---|---|
| locale | Required. A Locale object. |
Technical Details
| Returns: | A reference to the Scanner object that this method belongs to, which allows for chaining configuration methods. An example of chaining is myObj.useLocale(Language.GERMAN).useDelimiter(",");. |
|---|