【问题标题】:Naming multiple strings with an incremented count使用递增计数命名多个字符串
【发布时间】:2012-11-30 06:21:11
【问题描述】:

我想命名一个具有递增计数的多个字符串 示例:字符串 str1、str2、str3、str4、str5、str6 等 这不是它的确切情况,但它是我能想到的最简单的例子

public static void main(String[] args) {
    for(int i = 0; i<10;i++)
        String str[i] = " "; // i want to name the String str1,str2,str3
    }
}

这是我为尝试完成此任务而创建的基本 for 循环,但它不起作用。我还能如何用循环命名多个字符串

澄清并添加更多以防万一;我有一堂课:

public Player(String playerName, boolean isDealer){}

&&我有创建每个播放器的方法

  int amount; //amount of players

  for (int i = 0; i < amount; i++) {
    if(i == dealer){continue;}
    System.out.println("What is the name of player " + i + "?");
    playerName = IO.readString();
            isDealer = false;
        Player player.valueAt(i); //creating player1,player2,player3,playeri

        }

【问题讨论】:

  • 你考虑过使用数组吗?这样,你可以说:'Str[0]'、'Str[1]'、'Str[2]'...
  • 在这种情况下,数组是最好的选择。如果您绝对需要这种命名,则需要使用另一个程序创建它并复制并粘贴输出。
  • 由于您是新手,我想指出的是,当您觉得自己得到了答案时,您必须将该答案标记为已接受。

标签: java string loops for-loop


【解决方案1】:

您的要求至少不能由 java 完成,但您还有其他选择,例如:

1。数组

String[] str = new String[no-of-element];
for(int i = 0; i<str.length();i++){
  str[i] = "str"+i; 
}

2。收藏

您可以使用collection 来满足您的要求

【讨论】:

    【解决方案2】:

    字符串不会以这种方式工作,您需要考虑创建字符串数组

    【讨论】:

      【解决方案3】:

      其他答案指出这在 JAVA 中是不可能的。但这里有一些解决方案:

      第一种方式:使用MapKey 作为您生成的名称,如str1、str2....和value 作为您的字符串对象。然后当你想使用它们时,你可以使用get(name_of_str) 来获取你正在寻找的对象。

      第二种方式: 否则。但如果你仍然想这样做,请尝试使用Metaprogramming

      【讨论】:

      • 使用 Map&lt;String,Player&gt; 这应该可以解决您的目的。 String 是玩家名称,Player 是您创建的实例。
      猜你喜欢
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多