我想做的是用array-list执行两个集合接口的方法,即,我已经创建了一个简单的菜单。
首先我选择了第一种情况,所以数组列表'arr‘在其中添加了"ABC“,然后我选择了第二种情况,似乎我得到了错误的答案。对于第二种情况,arr为null。
第二种情况下我想要的答案:[ABC,7,AB,34]
我得到的答案是:[7,AB,34]
import java.util.*;
class ArrayList
{
public static void main(String [] args)
{
Scanner inp = new Scanner(System.in);
int ch=0;
do
{
System.out.println("Press 1,add.");
System.out.println("Press 2,addAll.");
System.out.println("Enter your choice?");
Integer choice = inp.nextInt();
ArrayList <String>arr = new ArrayList<String>();
switch(choice)
{
case 1:
arr.add("ABC");
System.out.println("Enter the elements in an arraylist:");
int i=0;
while(i<2)
{
String obj=inp.next();
arr.add(obj);
i++;
}
System.out.println("The elements are:" +arr);
break;
case 2:
ArrayList <String>arr1=new ArrayList<String>();
arr.add("7");
arr1.add("AB");
arr1.add("34");
arr.addAll(arr1);
System.out.println("The elements are:" +arr);
break;
}
System.out.printf("Press 0 to continue?");
ch=inp.nextInt();
}while(ch==0);
}
}发布于 2017-01-08 02:28:31
您应该在case1之外添加arr.add(“ABC”);,这样case2就可以看到它了。
import java.util.*;
class NewTestC
{
public static void main(String [] args)
{
Scanner inp = new Scanner(System.in);
int ch=0;
do
{
System.out.println("Press 1,add.");
System.out.println("Press 2,addAll.");
System.out.println("Enter your choice?");
Integer choice = inp.nextInt();
ArrayList <String>arr = new ArrayList<String>();
arr.add("ABC");
switch(choice)
{
case 1:
System.out.println("Enter the elements in an arraylist:");
int i=0;
while(i<2)
{
String obj=inp.next();
arr.add(obj);
i++;
}
System.out.println("The elements are:" +arr);
break;
case 2:
ArrayList <String>arr1=new ArrayList<String>();
arr.add("7");
arr1.add("AB");
arr1.add("34");
arr.addAll(arr1);
System.out.println("The elements are:" +arr);
break;
}
System.out.printf("Press 0 to continue?");
ch=inp.nextInt();
}while(ch==0);
}
}https://stackoverflow.com/questions/41524866
复制相似问题