I need to parse an input string into a new class object consisting of two floats. I do have a solution but it looks cumbersome. I wondered if there is a more elegant way to do it, esp. if the string splits only to 2 substrings and a cycle seems to be a bit of overkill?
my class:
public class Float2 {
public float width;
public float height;
}
my method to parse the input string into a class object:
public Float2 parseStringToFloat2(String inputstring) {
String[] stringarray = inputstring.split(",");
float[] floats = new float[2];
for (int i = 0; i <2; ++i) {
float number = Float.parseFloat(stringarray[i]);
floats[i] = number;
}
return new Float2(floats[0], floats[1]);
}
I do think the loop is an overkill if you know for sure there will by only 2 parts. Maybe try this:
public Float2 parseStringToFloat2(String inputstring){
String[] stringarray = inputstring.split(",");
try {
return new Float2(Float.parseFloat(stringarray[0]), Float.parseFloat(stringarray[1]));
} catch (Exception e) {
// catch logic
}
return null;
}
As said in a comment, you should also use try catch logic in case of a conversion error.
Another solution would be to use a Scanner
. It is a more flexible solution if you need Locale-specific parsing (it uses the default locale without setting it, which could be problematic if a ,
is a decimal separator there). Also if you use a regex delim, the pattern can be precompiled to be faster.
public static Optional<Float2> parseStringToFloat2(String inputstring) {
final Scanner in = new Scanner(inputstring).useLocale(Locale.US).useDelimiter(", ");
// in.useDelimiter(Pattern.compile("\\s*,\\s*"));
try {
return Optional.of(new Float2(in.nextFloat(), in.nextFloat()));
} catch (NoSuchElementException e) {
return Optional.empty();
}
}
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.