I have one list now. I want to remove two object when I used command line.
Ex)
javac Main.java
java Main 2 3
a v i
I try changed code .I can not do that. Please help me.
Condition
using Arraylist
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] s = {"a", "v", "c", "e", "i"};
List<String> list = new ArrayList<>(s.length);
for (String string : s) {
list.add(string);
}
try {
int index = Integer.parseInt(args[0]);
list.remove(index);
for (String string : list)
System.out.println(string);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("it is not good");
}catch (IllegalArgumentException e){
System.out.println("it is not good");
}catch (IndexOutOfBoundsException e){
System.out.println("it is not good");
}
}
}
CodePudding user response:
Try the following code. Your code only takes ONE argument args[0]. Instead I used a for loop to iterate all given arguments. However, this will not work in the way you are thinking, because the index is shifted when an item is removed.
public static void main(String[] args) {
String[] s = {"a", "v", "c", "e", "i"};
List<String> list = new ArrayList<>(s.length);
for (String string : s) {
list.add(string);
}
try {
for (int i = 0; i< args.length; i ){
int index = Integer.parseInt(args[i]);
list.remove(index);
}
for (String string : list)
System.out.println(string);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("it is not good");
}catch (IllegalArgumentException e){
System.out.println("it is not good");
}catch (IndexOutOfBoundsException e){
System.out.println("it is not good");
}
}
Instead, if you use the following, it adjusts the indexes from the arguments provided based on the number of items removed.
for (int i = 0; i< args.length; i ){
int index = Integer.parseInt(args[i])-i;
list.remove(index);
}
I just realised the code does not account for indexes that are not sorted. Thus, I added some code that will perform the sorting for you. Use the following code instead.
int[] numbers = Arrays.stream(args).mapToInt(Integer::parseInt).toArray(); //convert args to int array
System.out.println(Arrays.toString(numbers)); //shows your arguments
Arrays.sort(numbers); //sort your indexes in ascending order
System.out.println(Arrays.toString(numbers)); //shows sorted arguments
for (int i = 0; i< numbers.length; i ){
list.remove(numbers[i] - i);
}
for (String string : list)
System.out.println(string);
note, if you dont want to use numbers[i]-i
you could instead iterate the array starting from the back of the array and use numbers[i] instead
for (int i = numbers.length-1; i>=0; i--){
list.remove(numbers[i]);
}