超过“ 9999”时,将数字字符串值重置为“ 1”

时间:2018-10-01 06:27:35

标签: java android

如何将字符串号9999重置为0001,该字符串数限制为4位:

String currentNumber = "9999";

String incremented = String.format("%0" + currentNumber.length() + "d",
                Integer.parseInt(currentNumber) + 1);

上面的结果将给我10000。

3 个答案:

答案 0 :(得分:3)

使用模运算符:

String currentNumber = "9999";

String incremented = String.format("%0" + currentNumber.length() + "d",
                (Integer.parseInt(currentNumber) + 1) % 9999);

这是当您为currentNumber使用适当的打字机时的样子:

Integer currentNumber = 9999;
Integer moduledNumber = (currentNumber + 1) % 9999;
String incremented = String.format("%0" + currentNumber.toString().length() + "d", moduledNumber);

答案 1 :(得分:1)

您可以为此创建自定义方法

getThresholds(colors) {
  return [{
    dType: "threshold",
    from: 0,
    to: 30,
    color: colors[0]
  },
  {
    dType: "threshold",
    from: 30,
    to: 70,
    color: colors[1]
  },
  {
    dType: "threshold",
    from: 70,
    to: 120,
    color: colors[2]
  }]
}

const colors = ["#219131", "#F2910A", "#D91427"]

thresholds : getThresholds(colors)

thresholds : getThresholds(colors.reverse())

答案 2 :(得分:0)

为什么不使用if语句?
试试这个

if (Integer.parseInt(currentNumber) > Integer.parseInt(maxNumber))
currentNumber = "0001"

希望它会为您提供帮助