2

I don't understande why this is not working: (method is taken from HERE on SO).

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;
}

and neither this one:-

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;
    }
}

from time to time I get -1 B from the request (this is normal), that is never changed in n.a. (....my question).

Does anyone have an idea?

Community
  • 1
  • 1
dentex
  • 3,223
  • 4
  • 28
  • 47
  • 1
    Consider first telling us exactly what you're trying to do with this code. – Hovercraft Full Of Eels Feb 11 '13 at 17:49
  • thanks for the minus 1. I was just now editing to add the link from SO. You've been light fast. Anyway the line `from time to time I get -1 B from the request (this is normal), that is never changed in n.a. (...my question).` explains that I want to change `-1 B` returned from the linked method in `n.a.` – dentex Feb 11 '13 at 17:52
  • Fair enough. I was thinking that the piece of code in common by the two blocks explains someway. – dentex Feb 11 '13 at 17:55

1 Answers1

2

Here's your problem:

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

When bytes equals -1 (which is less than unit in either case), it returns -1 B without ever getting to the line hr = hr.replace("-1 B", "n.a.");.

It would be better to have one return statement at the end, assign String hr = bytes + " B" in the if, and add an else block around the next three lines. Then after that block, the hr.replace() call will execute either way, and then return the value.

  • I'm going to try now. Thanks. I don't know why I didn't receive mail notice to your answer! – dentex Feb 12 '13 at 11:29