代码之家  ›  专栏  ›  技术社区  ›  Alvin

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

  •  -2
  • Alvin  · 技术社区  · 6 年前

    如何将字符串编号9999重置为0001(限制为4位):

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

    上面的结果将给我10000英镑。

    3 回复  |  直到 6 年前
        1
  •  3
  •   user987339 jbandi    6 年前

    使用模运算符:

    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);
    
        2
  •  1
  •   Tarun darkpbj    5 年前

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

    String increment(String num,int incrementBy) //incrementBy  is an integer by which you want to increment
    {  
        int numInt=Integer.parseInt(num);
        numInt+=incrementBy;
        if (numInt>9999)
            return String.valueOf(numInt%9999);
        return String.valueOf(numInt);
    }
    
        3
  •  0
  •   Milad    6 年前

    为什么不用if语句?

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

    希望对你有帮助