【问题标题】:Add int to end of string name?将 int 添加到字符串名称的末尾?
【发布时间】:2011-06-18 21:16:16
【问题描述】:

所以我正在寻找一种临时存储值的方法,以便在必要时可以将其删除(我可能会以完全错误的方式来解决这个问题,如果我错了,请纠正我!)

我创建了 18 个字符串:info1、info2、info3 等...

我想根据用户所处的位置将每个设置为某个值,这就是我的想象。

hole = 1;
info + hole = current; <--- current is a string with a value already.
hole++;

(所以 info1 = 当前值 1)

info + hole = current; <--- current is a new string with a new value similar to the first.
hole++;

(所以 info2 = 当前值 2)

如果您需要更多代码,请告诉我。我决定我会跳过它,而不用这个问题打扰社区,所以我删除了代码,然后决定不,我真的想要这个功能。如果需要,我会很快重写它。

【问题讨论】:

    标签: java string int


    【解决方案1】:

    这是一个错误的方法

    info + 1 = 2;
    

    不一样
    info1 = 2;
    

    你需要把东西放在一个数组中然后进行操作

    所以为你的 18 个字符串定义一个数组为

    String[] info = new String[18];
    

    然后再做

    info[hole-1] = current;
    

    这是关于 java 中基本数组的不错的教程,仅供参考http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

    【讨论】:

    • 它应该是info[hole-1] = current,因为字符串数组是零索引的。
    【解决方案2】:

    创建一个String 数组:

    String[] info = new String[18];
    // ....
    hole = 1;
    info[hole] = current;
    hole++;
    

    【讨论】:

      【解决方案3】:

      这在语法上是错误的。在处理大量变量时,您应该使用数组或列表。在这种情况下,创建一个 String 数组。你的代码应该是这样的:

      String info[] = new String[18];
      String current = "something";
      int hole = 1;
      info[hole-1] = current;  // string gets copied, no "same memory address" involved
      hole++;
      

      更短的代码 sn-p:

      String info[] = new String[18], current = "something";
      int hole = 1;
      info[hole++ - 1] = current; // hole's value is used, THEN it is incremented
      

      通过this official documentation tutorial了解更多信息。

      【讨论】:

        猜你喜欢
        • 2012-08-03
        • 2012-08-06
        • 2021-01-04
        • 1970-01-01
        • 2013-02-02
        • 2015-07-02
        • 2021-10-06
        • 1970-01-01
        • 2011-07-22
        相关资源
        最近更新 更多