简体   繁体   English

有效地将字符串解析为 class object 在 java 中有 2 个浮点数

[英]Efficiently parse string to a class object with 2 floats in java

I need to parse an input string into a new class object consisting of two floats.我需要将一个输入字符串解析成一个新的 class object 由两个浮点数组成。 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?如果字符串仅拆分为 2 个子字符串并且一个循环似乎有点矫枉过正?

my class:我的 class:

public class Float2 {
    public float width;
    public float height;
}

my method to parse the input string into a class object:我将输入字符串解析为 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.如果您确定只有 2 个部分,我确实认为循环是一种矫枉过正。 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.正如评论中所说,如果出现转换错误,您还应该使用 try catch 逻辑。

Another solution would be to use a Scanner .另一种解决方案是使用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).如果您需要特定于语言环境的解析,这是一个更灵活的解决方案(它使用默认语言环境而不设置它,如果 a ,是那里的小数分隔符,这可能会出现问题)。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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