我是java新手,做得不好,需要一些帮助。我有一个名为“RestaurantObject”的类,我正在尝试从我的主要类中创建一个对象。我遇到了问题,因为该对象中的一个变量是一个数组。我真的不确定该把它放在那里。
这是我的主要内容:
public class MyRestaurantObject {
public static void main(String[] args) {
RestaurantObject mcDonalds = new RestaurantObject("McDonalds", "McDonalds Menu", **WHAT GOES HERE?**);
以下是我的班级“RestaurantObjects”的代码
public class RestaurantObject {
private static final Object[] String = null;
private String restaurantName;
private String menu;
private String [] employees;
public RestaurantObject(String name, String menu, String [] employees){
setRestaurantName(name);
setMenu(menu);
setEmployees(employees);
}
//restaurantName
public String getRestaurantName(){
return restaurantName;
}
private void setRestaurantName(String name){
restaurantName = name;
}
//menu
public String getMenu(){
return menu;
}
private void setMenu(String menu){
this.menu = menu;
}
//employees
public String[] getEmployees(){
return employees;
}
private void setEmployees(String [] employees){
this.employees = employees;
}
}
我知道我做得不对。请帮忙!
谢谢!
另外,如果我的任何术语有误,请纠正我。
答案 0 :(得分:2)
只需在第三个参数中传递一个新的字符串数组。
RestaurantObject mcDonalds = new RestaurantObject("McDonalds", "McDonalds Menu", new String[] {"Value1", "Value2"});
答案 1 :(得分:1)
我猜你还没有学过Java varargs,但这是一个使用它们的完美案例。然后你可以去
public RestaurantObject(String name, String menu, String...employees) {
setRestaurantName(name);
setMenu(menu);
setEmployees(employees);
}
以后,
RestaurantObject mcDonalds = new RestaurantObject(
"McDonalds", "McDonalds Menu", "John Doe", "Jane Doe");
如果您还没有使用或尚未学习varargs,@ fvu版本2是我的首选。
答案 2 :(得分:0)
有两种选择:
1在创建RestaurantObject
之前创建数组(该类应该只是被称为Restaurant
String[] emplArr = new String[]{ "Bob", "Alice", "Fred"};
RestaurantObject mcDonalds;
mcDonalds = new RestaurantObject("McDonalds", "McDonalds Menu", emplArr);
2在RestaurantObject
的构造函数调用中使用静态初始化器初始化数组
RestaurantObject mcDonalds;
mcDonalds = new RestaurantObject("McDonalds", "McDonalds Menu", new String[]{ "Bob", "Alice", "Fred"});
答案 3 :(得分:0)
你可以做到
RestaurantObject mcDonalds = new RestaurantObject(
"McDonalds", "McDonalds Menu", new String[] {"John Doe", "Jane Doe"});
或
String[] employees = new String[] {"John Doe", "Jane Doe"};
RestaurantObject mcDonalds = new RestaurantObject(
"McDonalds", "McDonalds Menu", employees);
或
String[] employees = new String[2];
employees[0] = "John Doe";
employees[1] = "Jane Doe";
RestaurantObject mcDonalds = new RestaurantObject(
"McDonalds", "McDonalds Menu", employees);
关于后者的说明:当你创建这样的数组时,你必须知道它的大小,这有时会非常烦人。这就是为什么许多人更喜欢使用ArrayList
s,其行为或多或少像弹性数组,即在添加n项时自动扩展。