java - 用户创建新实例
问题描述
作为最精通 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() );
}
}
解决方案
你应该用收集来做(正如评论中已经提到的)。我还假设您应该让您的方法返回您创建的实例:
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
推荐阅读
- python - 如何显示从pycharm中导入的库创建的对象的自动完成?
- javascript - 如何使用鼠标滚动在其他 div 后面显示一个 div
- sql - Oracle SQL - 如何返回每个 ID 的最早/最短日期的记录
- xcode - 在正在观看的播放屏幕之间滑动会空白其他屏幕
- python - Pandas 不适用于 Spark 并行代码
- kubernetes - 使用 helm 安装 kubernetes-dashboard 失败
- c# - 如何在 c# 中将 DateTime.Now 转换为 0 到 1 十进制格式
- .net - 使用 WPF ElementHost 托管的 WPF 控件仅在 Win 7 下存在鼠标滚轮问题
- ms-access - 如何从“子表单”中选择的表中删除特定记录?
- javafx - 按下 F4 时禁用 ComboBox 下拉菜单