Java,结合类

时间:2014-06-08 14:11:22

标签: java class printing

我遇到了一个问题,最近选择了Java,现在我正在做一些任务,但似乎无法弄清楚解决方案,我得到的输出在下面,我无法弄清楚如何改为那个随机菜单@ somenumber,例如第一个是午餐,是的,我知道我仍然需要实际的菜单项打印

餐厅'Awsome'

  • 菜单:菜单@ 2389b9bd
  • 菜单:菜单@ 27013985

餐厅'好的'

  • 菜单:菜单@ 41675ec4
  • 菜单:菜单@ 697eb767

餐厅'Lame'

  • 菜单:菜单@ 7e3b014c
  • 菜单:菜单@ 53d26552

代码:

class RestaurantTest {

   public static Restaurant[] init()
   {
      MenuItem[] AwsomeLunch = { new MenuItem ("Chicken", 5.2 ), new MenuItem ("Sarma", 3.1) };
      MenuItem[] AwsomeDinner = { new MenuItem ("Steak", 10.2 ), new MenuItem ("Squid", 8.2) };   
      MenuItem[] OkayLunch = { new MenuItem ("Kebab", 6.1 ), new MenuItem ("Ćevapi", 3.7) };  
      MenuItem[] OkayDinner = { new MenuItem ("Sharksteak", 11.4 ), new MenuItem ("Pizza", 6.2) };
      MenuItem[] LameLunch = { new MenuItem ("Burek", 2.5 ), new MenuItem ("Wiener Schiniztel", 4.3) };
      MenuItem[] LameDinner = { new MenuItem ("Octopus", 11.4 ), new MenuItem ("Kalja", 0.1) };


      Menu[] MenuAwsome = { new Menu ("Lunch", AwsomeLunch), new Menu("Dinner", AwsomeDinner) };
      Menu[] MenuOkay = { new Menu ("Lunch", OkayLunch), new Menu("Dinner", OkayDinner) };
      Menu[] MenuLame = { new Menu ("Lunch", LameLunch), new Menu("Dinner", LameDinner) };

      Restaurant[] listOfRestaurants = { new Restaurant ("Awsome", "Vukovarska 111", MenuAwsome), new Restaurant ("Okay", "Stradun 222", MenuOkay), new Restaurant ("Lame", "Ilica 333", MenuLame)};
      return listOfRestaurants;

   }  
   public static void main (String[] arguments){

      Restaurant[] listOfRestaurants = init();

      Restaurant awsome = listOfRestaurants[0];
      Restaurant okay = listOfRestaurants[1];
      Restaurant lame = listOfRestaurants[2];

      System.out.println(awsome.getName());



      System.out.println("---------------------------------------");
      System.out.println();
      System.out.println("Running 'Restaurant Menu Search':");
      System.out.println();
      System.out.println("---------------------------------------");

      for (int i=0; i<3; i++) {
          System.out.println("Restaurant '" + listOfRestaurants[i].getName() + "'"); 

          for (int j=0; j<2; j++) {
            System.out.println("- Menu:" +  (listOfRestaurants[i].getMenu())[j]);
         }






      }





   } 
}

2 个答案:

答案 0 :(得分:0)

基本上你的问题就在这一行:

System.out.println("- Menu:" +  (listOfRestaurants[i].getMenu())[j]);

您获得的随机数是类型菜单对象的参考地址。此数字表示您正在打印对象Menu的toString(),如果没有覆盖,则打印对象的引用。所以要解决这个问题,你可以为菜单调用getName()(如果定义的话),所以你的语句将是这样的:

System.out.println("- Menu:" +  (listOfRestaurants[i].getMenu())[j].getName());

或者定义一个toString(),它将打印菜单名称,如下所示:

Stirng toString(){
    return this.name;
}

答案 1 :(得分:0)

您应该从Menu类打印一些属性,而不是像Menu:Menu@7e3b014c这样的对象引用。例如

Menu m = listOfRestaurants[i].getMenu()[j];
System.out.println("Menu "+m.getName());
MenuItem[] launch = m.getLaunch();
for (MenuItem mi: launch)
  System.out.println("MenuItem "+mi.getName()+",  price "+mi.getPrice());