0

我需要帮助让这种方法接受混合数字,例如(2 1/2)存储为一个变量而不是两个。目前我有来自两个单独的文本字段的 int 和 frac。

public double convertFrac(int whole, String frac){
        if (frac == null || frac.equals(""))
            return whole;
        String[] parts = frac.split("/");
        return whole + (double)Integer.parseInt(parts[0]) / (double)Integer.parseInt(parts[1]);
    }

感谢 Bohemian 的建议,编辑了代码。

按照您的某些标准,它可能很笨重,但我让它工作了=D

public static double convertFrac(String frac){
        String wholeStr, num, denom, fraction;
        int whole = 0;
        String[] parts = frac.split(" ");
        wholeStr = parts[0];
        whole = Integer.parseInt(wholeStr);

        if(parts.length == 1){
            return whole;
        }

        wholeStr = parts[0];
        whole = Integer.parseInt(parts[0]);
        fraction = parts[1];
        String[] fracParts = fraction.split("/");
        num = fracParts[0];
        denom = fracParts[1];

        return whole + (double)Integer.parseInt(fracParts[0]) / (double)Integer.parseInt(fracParts[1]);
    }
4

1 回答 1

4

这是错误 #1:

if(frac == ""){ // tests if frac is the same object as the blank constant

你必须使用

if(frac.equals("")){ // tests if fraq is blank


这是错误 #2:

num = Integer.parseInt(frac); // will explode if frac is actually a fraction


而不是你所拥有的,我会将其简化为:

public double convertFrac(int whole, String frac) {
    if (frac == null || frac.equals(""))
        return whole;
    String[] parts = frac.split("/");
    return whole + (double)Integer.parseInt(parts[0]) / (double)Integer.parseInt(parts[1]);
}

你不应该考虑frac只有一个数字,因为它没有意义。要么是空白,要么是一小部分。

于 2013-01-13T12:56:05.923 回答