I know this has been asked before¹ but responses don't seem to cover all corner cases.
I tried implementing the suggestion¹ with the test case
String("Doubles -1.0, 0, 1, 1.12345 and 2.50")
Which should return
[-1, 0, 1, 1.12345, 2.50]:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Locale;
public class Main
{
public static void main(String[] args) {
String string = new String("Doubles -1.0, 0, 1, 1.12345 and 2.50");
System.out.println(string);
ArrayList<Double> doubles = getDoublesFromString(string);
System.out.println(doubles);
}
public static ArrayList<Double> getDoublesFromString(String string){
Scanner parser = new Scanner(string);
parser.useLocale(Locale.US);
ArrayList<Double> doubles = new ArrayList<Double>();
double currentDouble;
while (parser.hasNext()){
if(parser.hasNextDouble()){
currentDouble = parser.nextDouble();
doubles.add(currentDouble);
}
else {
parser.next();
}
}
parser.close();
return doubles;
}
}
Instead code above returns [1.12345, 2.5].
Did I implement it wrong? What's the fix for catching negative and 0's?
,in your string. By default the scanner will split the string on whitespace. Therefore, the first three doubles are read as-1.0,,0,and1,. The comma prevent those from being seen as double by the scanner.Locale.USso I was trying to test it as well. It will be hard to build something "universal" using scanner then, I'll keep up with the regex solution provided by Tim