gpt4 book ai didi

java - 由用户创建新实例

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

作为最熟练的 JAVA 用户,您可能已经看到,这是行不通的。 sb 不能同时用作Stringinstance。但你一定也知道我在这里想做什么。我尝试让用户创建 Cook 类的新实例。但由于 cook1cook2 已经存在(已在代码中创建),我现在希望用户创建一个新的。不知何故,sb必须充当变量,导致潜在的下一个厨师必须插入为cook4等......在 Java 中如何做到这一点???

package kebabStore;

import java.util.Scanner;

public class NewCook {
static String newcookname;
static String newcookaddress;
static String newcookpobox;
static String newcooktown;
static int newcooktaxnumber;

static Scanner scanner = new Scanner(System.in);

public static void newcook () {
Cook.numberofcooks++; //this works, this counter adds up.
System.out.println("Enter name new cook");

newcookname = scanner.nextLine();

System.out.println("enter address new cook");

newcookaddress = scanner.nextLine();

System.out.println("Enter PO Box new cook");

newcookpobox = scanner.nextLine();

System.out.println("Enter town new cook?");

newcooktown = scanner.nextLine();

System.out.println("Enter tax number new cook");

newcooktaxnumber = scanner.nextInt();

StringBuilder sb = new StringBuilder("cook");
sb.insert(3,Cook.numberofcooks);

System.out.println(sb); // check if the constructor works, yes it does!! it says "cook3"

Cook sb = new Cook (newcookname, newcookaddress, newcookpobox, newcooktown, newcooktaxnumber);

System.out.println("A new cook has been hired " +sb.getName() + ", living in " + sb.getTown() );

}
}

最佳答案

你应该通过收集来做到这一点(正如评论中已经提到的)。我还假设您应该让您的方法返回您创建的实例:

public static Cook newcook() {
//all your logic is the same
return sb;
}

然后,在调用方法 newcook 的范围开始处:

List<Cook> cooks = new ArrayList<Cook>();
...
cooks.add(cook1);
cooks.add(cook2); // Since they already exist, as you mentioned

cooks.add(newcook()); // inserts third

关于java - 由用户创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408034/

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