java - 让用户创建多个对象

标签 java switch-statement

我正在尝试编写一个程序,让用户创建 2 个仓库。 我将它放在 switch 语句中,但是当它完成并且我返回创建第二个仓库时,它会覆盖 depot1。

我不确定如何创建 2 个独立的仓库。

do {
    System.out.println("(1) Add depot number 1 ");
    System.out.println("(2) Remove a depot");
    System.out.println("(3) Exit program");
    option = console.nextInt();

    switch (option) {
        case 1: 
            depot1 = new Depot();                           
            if (depot1.checkDepot() == true){
                System.out.println("Enter Depots name");
                n = console.next();
                depot1.setDepotName(n);                                
            }
            else{
                System.out.println("Error only 2  depots allowed");
            }
            break;

        case 2:
        case 3:
            System.exit(0);
    }
}
while (option !=3);
public class Depot 
{
   private String name;
   private Product product1, product2, product3;
   static int depotCounter = 0;

   // Constructor to count depot objects 
    public Depot(){
        depotCounter++;
    }
   // Method to make sure no more than 2 depots are created
    public boolean checkDepot(){
        if (depotCounter <= 2){
            return true;
        }
        else{
            return false;
        }

是我的仓库类,我有一个计数器和一个检查仓库,以确保只创建 2 个。

它很好地创建了 depot1,但是当我再次进入该语句并单击 (1) 时,它会在对象 depot1 上重写一个新名称

最佳答案

当您输入选项 1 时,它所做的只是执行第一个“switch-case”中的代码。在那里,您始终使用 depot1 作为变量。顺便说一句,退出 switch 语句后,您的仓库无论如何都会丢失,因为您在该 block 中声明了它。你可以做的是这样的:

do {
    Depot depot1;
    Depot depot2;
    //Your code for the menu, e.g. selecting what the user wants to do
    switch (option) {
        case 1 :
            if (depot1 == null) {
                depot1 = new Depot()
                //Do what you want to do with your depot
            } else if (depot2 == null) {
                depot2 = new Depot()
                //Same as above
            }
            break;
            //Rest of the switch statement
    }
} while (option != 3)

我在那里所做的只是为仓库使用 2 个不同的变量,当您想创建一个新的仓库时,您首先检查是否已经创建了一个仓库(例如,如果 depot1 指向某个对象,那么如果 depot1 = = null为false)然后创建对应的depot。如果您根本没有创建 depot,则 depot1 为 null,因此您创建 depot1。如果您已经创建了 depot1,则 depot1 == null 为 false,因此它跳转到第二个 if block ,检查 depot2 是否为 null,因此它创建 depot2。当已经有 2 个仓库时,它什么也不做。

如果您想要 2 个以上的仓库,Backpack 在他的回答中所说的就是您的选择。

总结一下: a) 您的软件仓库需要不同的变量,而不仅仅是一个,因此您不能覆盖当前的软件仓库。 b) 如果您希望对象在 switch 语句之外持续存在,则需要在 switch 语句之外声明它们。变量仅在您声明它们的 block 内“存在”。

关于java - 让用户创建多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611318/

相关文章:

java - 如何在锁定屏幕上添加 MediaPlayer 控件?

java - 使用 void 方法添加按钮

java - 我如何对 toCompare() 方法进行单元测试,比较 2 个对象?

ios - 不确定如何避免 Swift switch 的默认语句中出现垃圾

java - 从文本文件中读取值并分为字符串和 double

java - Android程序崩溃空指针异常

C程序,切换菜单死循环

C# 在 lambda 表达式中切换

javascript - Break 不适用于我的 switch 语句

c - Switch 语句 - 换行和正确缩进后的行