首页 > 解决方案 > 用户创建新实例

问题描述

作为最精通 JAVA 的你,可能已经看到了,这是行不通的。sb不能同时用作 aString和 an instance。但你也一定知道我在这里要做什么。我尝试让用户创建一个新instance的类Cook。但是既然cook1并且cook2已经存在(已经在代码中创建),我现在希望用户创建一个新的。不知何故,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() );           

    }
}

标签: javavariablesinstance

解决方案


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

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

推荐阅读