如何在JAVA中使用Switch case在数组列表中添加值

问题描述 投票:0回答:1

我是 Java 新手,我有一个问题。如何在 Switch 情况下在 arrayList 中添加值或索引?

我试过没有开关盒,它会工作得很好,但在开关盒中,根本不起作用!我的代码可以运行,但我无法添加值,例如在情况 1 中。

这是我的代码。

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;


    }
}
}

我尝试做的是使数组动态化,并且我可以在 Switch 中添加或删除而不丢失值。

请为我糟糕的英语道歉。

我尝试让用户输入内容但没有成功。我的意思是,每次用户输入时,值不会保存在添加数组列表中。

我觉得我已经很接近了,但我也输了。

java arraylist
1个回答
0
投票

您的

cars
列表对于名为
menu()
的方法的一次调用是本地的。

当您再次调用该方法时,它会获得不同的

cars
列表。

您可以通过在

menu()
方法的单次调用中使用循环来解决此问题 - 例如
do-while
循环。然后每次循环都将使用相同的列表。

© www.soinside.com 2019 - 2024. All rights reserved.