gpt4 book ai didi

java - 让用户创建多个对象

转载 作者:行者123 更新时间:2023-12-02 10:01:19 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,让用户创建 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com