【问题标题】:creating new instance by user用户创建新实例
【发布时间】:2019-12-19 10:42:59
【问题描述】:

作为最精通 JAVA 的您,可能已经看到,这是行不通的。 sb 不能同时用作Stringinstance。但你也一定知道我在这里要做什么。我尝试让用户创建一个新的instanceCook。但是由于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() );           

    }
}

【问题讨论】:

  • 创建一个包含 Cook 实例的列表,每次创建时,将其添加到列表中
  • @Stultuske,是的,但是我如何创建一个?我想我不明白你的意思!我是否需要创建一个包含多个实例名称的列表,例如“cook3、cook4、cook5 等?并取出一个分配给新创建的实例???
  • 为什么您需要多个厨师变量?难道你不能将旧的厨师对象存储到一个集合中,然后使用厨师变量来保存一个新的厨师吗?

标签: java variables instance


【解决方案1】:

您应该通过收集来完成(正如 cmets 中已经提到的那样)。我还假设您应该让您的方法返回您创建的实例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多