java通过用户输入在数组中插入/删除元素
我是Java编程的新手。我想问一下,如何将用户的特定输入插入/删除到我生成的arraylist中。它应该会显示新的列表,我已经有了一个代码。。但效果不太好。。这是我的代码:
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
class New1 {
public static InputStreamReader r = new InputStreamReader (System.in);
public static BufferedReader inp = new BufferedReader(r);
public static void main (String args[]) throws Exception {
ArrayList employees = new ArrayList();
employees.add("A");
employees.add("B");
employees.add("C");
employees.add("D");
employees.add("E");
Scanner scan1 = new Scanner (System.in);
System.out.println ("Lists of Employees");
System.out.println ("What do you want to do?:");
System.out.println ("1 - Display list. \n2 - Insert New Name. \n3 - Delete an item. \n4 - Nothing." + "\n ");
int task = scan1.nextInt();
if (task==1) {
System.out.println ("Contents of Employees:" + employees);
} else if (task==2) {
do {
System.out.println("Current list is " + employees);
System.out.println("Add more? (y/n) ");
if (scan1.next().startsWith("y")) {
System.out.println("Enter : ");
employees.add(scan1.next());
} else {
break;
}
} while (true);
System.out.println("List is " + employees);
String[] arr = employees.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
我真的需要帮助><
# 1 楼答案
首先,代码中有一些编译时错误。 最后一行代码“}”缺失。班级街区没有关闭
第二,使用线下, String[]arr=(String[])雇员。toArray(新字符串[0]); 而不是 String[]arr=employees。toArray(新字符串[0])
因为toArray(新字符串[0])将返回一个对象,您将其存储在数组中。所以,你必须把它输入数组。现在,它可以正常工作了