Java-从动态数组/列表中添加并删除元素
只要用户输入/删除元素,我就需要动态数组。数组无法具有已经定义的长度或向用户询问长度。例如,用户决定添加5,数组将是:{5},然后用户添加34 {5,34},然后删除5,{34}。 有办法这样做吗?我一直在尝试使用列表,但是当我使用删除时,当我使用该代码时,当我使用Switch时,它就说“无法实现的语句”。 这是到目前为止的代码:
List<String> list = new ArrayList<>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current " + list);
System.out.println("Add more? (1) delete one? (2) exit (3)");
int a= stdin.nextInt();
switch(a){
case 1:
System.out.println("Enter: ");
list.add(stdin.next());
break;
case 2:
System.out.println("Enter: ");
list.remove(stdin.next());
break;
case 3:
break;
default:
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
I need my array to be dynamic, as long as the user enters/deletes elements. The array can't have the length already defined or ask the user the length. For example the user decides to add 5, the array would be: {5}, then the user adds 34 {5,34}, then deletes 5, {34}.
Is there a way of doing it? i've been trying with list but when i used if the remove one didn't work and when i use switch with this code it says "unreachable statement".
Here's the code so far:
List<String> list = new ArrayList<>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current " + list);
System.out.println("Add more? (1) delete one? (2) exit (3)");
int a= stdin.nextInt();
switch(a){
case 1:
System.out.println("Enter: ");
list.add(stdin.next());
break;
case 2:
System.out.println("Enter: ");
list.remove(stdin.next());
break;
case 3:
break;
default:
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试使用标签。
因此,基本上,您的情况下的断裂仅在循环时仅在外部开关语句中折断,而不是外部。
您可以在以下操作之前添加一个语句:
unexloop是标签。请尝试。
You can try to use label.
So basically the break in your case 3 only breaks outside switch statement but not outside the do while loop.
You can add a statement before do as below:
where outerloop is a label. Please try this.
我认为语句中的
有问题。
当您使用
break
关键字时,它是指您的switch
语句。因此,您永远不会到达循环的尽头。
尝试某些东西以
打破
循环I think there's a problem with your
while
statement.When you use the
break
keyword, it refers to yourswitch
statement.So you'll never reach the end of your loop.
Try something to implement something to
break
the loop