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));
breakout of of. Yourbreakstatements only end the execution of theswitchnot thedo .. while, hence all code beneath} while(true);cannot be reached. You could use a flagswitch = falseand set it to true within yourcase 3and then usewhile(!exit)to make the code reachable.