How can I add values or index in arrayList in a switch case?
I have tried without a switch case. It will work well, but in a switch case, it is not working at all! My code run, but I cant add values, for example in case 1.
Here's my code.
import java.util.ArrayList;
import java.util.Scanner;
public class Eqla3tech {
public static void main(String[] args) {
menu();
}
static void menu() {
ArrayList<String> cars = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("Add Student <1>");
System.out.println("remove Student <2>");
System.out.println("show list of students <3>");
System.out.println("how many students? <4>");
int num = input.nextInt();
input.nextLine();
switch(num) {
case 1:
System.out.println("write student name!!");
cars.add(input.next());
menu();
break;
case 2:
System.out.println("what number of index of student to remove");
int index = input.nextInt();
cars.remove(index);
menu();
break;
case 3:
System.out.println("Here's a list you have added.");
System.out.println(cars);
menu();
break;
case 4:
System.out.println("Here's haw many students");
System.out.println(cars.size());
menu();
break;
}
}
}
I try to make arrays as dynamic and I can add or remove from switch without losing values.
I have tried to make user enter input, but it did not work. I mean, every time the user enter input, the value is not saved in add arrayList.
I think I am close, but I am lost too.
Your cars
list is local to one call of the method called menu()
.
When you call that method again, it gets a different cars
list.
You can solve this by using a loop inside a single call of the menu()
method -- such as a do-while
loop. Then each pass through the loop will use the same list.