【问题标题】:How to make this Java (Android) String substitution?如何进行此 Java (Android) 字符串替换?
【发布时间】:2013-02-11 17:49:01
【问题描述】:

我不明白为什么这不起作用: (方法取自 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. 中永远不会改变(....我的问题)。

有人有想法吗?

【问题讨论】:

  • 考虑首先告诉我们你想用这段代码做什么。
  • 感谢负 1。我刚刚编辑以添加来自 SO 的链接。你已经很轻了。无论如何,from time to time I get -1 B from the request (this is normal), that is never changed in n.a. (...my question). 行解释说我想更改从n.a. 中的链接方法返回的-1 B
  • 很公平。我在想这两个块的共同代码可以解释一下。

标签: java android string substitution string-substitution


【解决方案1】:

这是你的问题:

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

bytes 等于-1(在任何一种情况下都小于unit)时,它会返回-1 B 而不会到达hr = hr.replace("-1 B", "n.a."); 行。

最好在末尾有一个return 语句,在if 中分配String hr = bytes + " B",并在接下来的三行周围添加一个else 块。然后在该块之后,hr.replace() 调用将以任一方式执行,然后返回值。

【讨论】:

  • 我现在要试试。谢谢。我不知道为什么我没有收到您回复的邮件通知!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 2023-02-23
  • 1970-01-01
  • 2011-01-30
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多