2

これが機能しない理由がわかりません:(メソッドはSOのHEREから取得されます)。

private String MakeSizeHumanReadable(int bytes, boolean si) {
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    String hr = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    hr = hr.replace("-1 B", "n.a.");
    return hr;
}

そして、これもありません:-

private String MakeSizeHumanReadable(int bytes, boolean si) {
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    String hr = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);

    Pattern minusPattern = Pattern.compile("-1 B");
    Matcher minusMatcher = minusPattern.matcher(hr);
    if (minusMatcher.find()) {
        return "n.a.";
    } else {
        return hr;
    }
}

時々私-1 Bはリクエストから取得します(これは正常です)、それは決して変更されませんn.a.(....私の質問)。

誰にもアイデアはありますか?

4

1 に答える 1

2

問題は次のとおりです。

if (bytes < unit) return bytes + " B";

bytesが -1 (どちらの場合よりも小さい)の場合、行に到達することなくunit戻ります。-1 Bhr = hr.replace("-1 B", "n.a.");

最後に1 つのreturnステートメントを配置し、 で代入String hr = bytes + " B"し、次の 3 行の周りにブロックifを追加することをお勧めします。elseその後、そのブロックの後、hr.replace()呼び出しはいずれかの方法で実行され、値が返されます。

于 2013-02-11T18:22:14.477 に答える