如何使String变量保持2个不同数组的值?

时间:2016-02-16 05:26:54

标签: java arrays

我希望变量String name能够保存数组的2个不同索引。 示例name = anArray[1] anArray[2] 这可能吗?

所以当我调用诸如

之类的打印语句时
System.out.println("Element at index 0: " + name);

我希望上面的语句打印anArray

的索引1和索引2中的值
 public static void main(String[] args) {

    String[] anArray;
    String name;

    // allocates memory for 10 integers
    anArray = new String[4];      
    // initialize first element
    anArray[0] = "mike";
    // initialize second element
    anArray[1] = "Rice";
    // and so forth
    anArray[2] ="John";
    anArray[3] = "Rice";

    name &= anArray[0] anArray[1];

    System.out.println("Element at index 0: "
                       + name);        
  }
 }

我收到的错误是:

  

test.java:22:错误:';'期望的名称& = anArray [0] anArray [1];

     

test.java:22:错误:不是声明名称& = anArray [0] anArray [1];

     

2个错误

2 个答案:

答案 0 :(得分:6)

name &= anArray[0] anArray[1];更改为name = anArray[0] + anArray[1];

答案 1 :(得分:0)

public static void main(String [] args){

String[] anArray;
String name;

// allocates memory for 10 integers
anArray = new String[4];      
// initialize first element
anArray[0] = "mike";
// initialize second element
anArray[1] = "Rice";
// and so forth
anArray[2] ="John";
anArray[3] = "Rice";

name = anArray[0]+","+ anArray[1];

System.out.println("Element at index 0: "
                   + name);        

}  }