简体   繁体   中英

creating new instance by user

As the most proficient JAVA users of you, already might have seen, this doesn't work. sb can not be used as a String and an instance at the same time. But you also must have figured what I am trying to do here. I try to let the user create a new instance of the class Cook . But since cook1 and cook2 already exist (created already in the code), I now want the user to create a new one. Somehow that sb has to be functioning as a variable, cause a potential next cook must be inserted as cook4 etc etc... How can such be done in 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() );           

    }
}

You should do it with collection (as was already mentioned in the comments). I also assume you should make your method return an instance you created:

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

Then, in the beginning of scope where you call the method 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM