使用for循环生成不同的对象名称

时间:2016-09-15 14:22:07

标签: java

我需要生成ID或对象名称。

public String[] getID(){

    String[] tempArray;

    for(int x=0; x<staffNum;x++){
        String temp = ("Att" + [x]);
        tempArray += temp;
        }
    return tempArray;
    }

所以for循环应该运行并用att添加迭代号。 那应该去一个数组。 但+是问题所在 它说令牌+上的语法错误 请问如何生成我的ID?

4 个答案:

答案 0 :(得分:2)

我相信你想要做的是:

public String[] getID(){
    // Create an array of String of length staffNum
    String[] tempArray = new String[staffNum];
    for(int x = 0; x < staffNum; x++){
        // Affect the value Att[x] to each element of my array
        tempArray[x] = String.format("Att[%d]", x);
    }
    return tempArray;
}

答案 1 :(得分:0)

使用

更改您的行
String temp = ("Att" + Integer.toString(x));

答案 2 :(得分:0)

语法已关闭。 您还必须初始化阵列。 该方法的命名并不理想。

//you're getting more than one id so indicate in method name
    public String[] getIds(){
            //initialize array
            String[] tempArray = new String[staffNum];
            //use i for indexes
            for(int i=0; i<staffNum; i++){
                //append the int onto the String
                String tempString = ("Att" + i);
            //set the array element
                tempArray[i] = tempString;
            }
        return tempArray;
    }

答案 3 :(得分:0)

  1. 初始化大小为staffNum的数组。

  2. 在循环中:

    • 使用temp = "Att" + x
    • 使用tempArray[x]= temp;
相关问题