首页 > 解决方案 > 让用户创建超过 1 个对象

问题描述

我正在尝试编写一个程序,让用户创建 2 个仓库。我将它放在 switch 语句中,但是当它完成并返回创建第二个 depot 时,它会覆盖 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 上重新写入一个新名称

标签: javaswitch-statement

解决方案


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

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 块,检查 depot2 是否为 null,它是,因此它创建 depot2。当已经有 2 个仓库时,它什么也不做。

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

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


推荐阅读