2016-09-15 181 views
-5

我需要生成ID或对象名称。使用for循环生成不同的对象名称

public String[] getID(){ 

    String[] tempArray; 

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

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

+3

'字符串温度= “ATT” + X; tempArray [x] = temp;'也需要初始化数组,使得'String [] tempArray = new String [staffNum];' – Orin

+2

这个代码在许多方面都是错误的。考虑阅读一些Java基础知识。 – null

回答

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; 
} 
0

更改符合

String temp = ("Att" + Integer.toString(x)); 
+1

他的代码有很多问题,虽然这是其中之一,但并不能解决所有问题。 – Orin

+0

我刚刚解决了他现在正在编译的编译时错误。不是其他人 – Abhijeet

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; 
    } 
0
  1. 初始化大小staffNum数组。

  2. 在循环:

    • 使用temp = "Att" + x
    • 使用tempArray[x]= temp;