-1

我是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;
}

}

我知道我做的不对。请帮忙!

谢谢!

另外,如果我的任何术语有误,请纠正我。

4

4 回答 4

2

只需在第三个参数中传递一个新的字符串数组。

RestaurantObject mcDonalds = new RestaurantObject("McDonalds", "McDonalds Menu", new String[] {"Value1", "Value2"});
于 2013-02-21T01:22:32.670 回答
1

我猜您还没有学习 Java 可变参数,但这是使用它们的完美案例。那你可以去

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");

如果您还不能使用或尚未学习可变参数,@fvu 版本 2 是我的首选。

于 2013-02-21T01:28:43.567 回答
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 项时它会自动扩展。

于 2013-02-21T01:23:32.323 回答
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"});
于 2013-02-21T01:21:32.660 回答