简体   繁体   中英

How to read doubles out of a scanner and put them into an arraylist

Scanner data = new Scanner("2.30 4.50 10.35 200.61 82.00");
ArrayList<Double> test = new ArrayList<Double>();

This is what I have, I do not need to take input from the mouse but I have to use a scanner to put my values in. I am testing a class that retrieves and stores data from and to an array list but I need to first get the values in the scanner into the list.

while(data.hasNextDouble()) {
    testUno.add(data.nextDouble()); 
}

I tried doing something like this afterwards but it did not work.

You need to set explicitly a Locale that uses a dot as decimal separator (like in your input values) otherwise if your default Locale uses for example a comma as separator your values won't be seen as double by the Scanner such that hasNextDouble() will return false , use Scanner#useLocale(locale) for this purpose as next:

Scanner data = new Scanner("2.30 4.50 10.35 200.61 82.00");
// Set the locale to US as it is a locale that uses a dot as decimal separator
data.useLocale(Locale.US);
List<Double> testUno = new ArrayList<>();
while(data.hasNextDouble()) {
    testUno.add(data.nextDouble());
}
System.out.println(testUno);

Output:

[2.3, 4.5, 10.35, 200.61, 82.0]

Scanner#useLocale(Locale locale)

Sets this scanner's locale to the specified locale. A scanner's locale affects many elements of its default primitive matching regular expressions ; see localized numbers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM