【发布时间】:2019-12-19 10:42:59
【问题描述】:
作为最精通 JAVA 的您,可能已经看到,这是行不通的。 sb 不能同时用作String 和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() );
}
}
【问题讨论】:
-
创建一个包含 Cook 实例的列表,每次创建时,将其添加到列表中
-
@Stultuske,是的,但是我如何创建一个?我想我不明白你的意思!我是否需要创建一个包含多个实例名称的列表,例如“cook3、cook4、cook5 等?并取出一个分配给新创建的实例???
-
为什么您需要多个厨师变量?难道你不能将旧的厨师对象存储到一个集合中,然后使用厨师变量来保存一个新的厨师吗?