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?
>Solution :
I would use a regex find all approach here:
String string = new String("Doubles -1.0, 0, 1, 1.12345 and 2.50");
List<String> nums = new ArrayList<>();
String pattern = "-?\\d+(?:\\.\\d+)?";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(string);
while (m.find()) {
nums.add(m.group());
}
System.out.println(nums); // [-1.0, 0, 1, 1.12345, 2.50]
By the way, your question makes use of the String constructor, which is seldom used, but is interesting to see, especially for those of us who never use it.
Here is an explanation of the regex pattern:
-? match an optional leading negative sign
\\d+ match a whole number
(?:\\.\\d+)? match an optional decimal component