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?