在主函数

时间:2018-04-08 09:39:28

标签: java arrays class oop

我想问一下,有没有办法可以在main函数中打印数组?例如,现在我的代码显示在下面

    Public static void main(String[] args)
{
        mainHobby Hobs = new mainHobby();
        System.out.println("My Hobbies are: ");
        for (int i = 0 ; i<Hobs.size ; i++)
        {
            int num = i + 1;
            System.out.println(num + ": " + Hobs.Hobby[i]);
        }
}

class mainHobby
{
    String[] Hobby = {"Reading", "Swimming", "Running"};
    int size = Hobby.length;
}

然而,我正在努力的是在主要功能下打印我的数组爱好。在评论部分打印数组爱好

        Public static void main(String[] args)
    {
            mainHobby Hobs = new mainHobby();
            //Print my array Hobby here
    }

class mainHobby
    {
        String[] Hobby = {"Reading", "Swimming", "Running"};
        int size = Hobby.length;

        System.out.println("My Hobbies are: ");
            for (int i = 0 ; i<Hobs.size ; i++)
            {
                int num = i + 1;
                System.out.println(num + ": " + Hobs.Hobby[i]);
            }
    }

2 个答案:

答案 0 :(得分:0)

public class Main
{
     static class MainHobby{
      String[] hobby = {"Reading", "Swimming", "Running"};
      int size = hobby.length;  

      void printHobby(){

          for(int i=0;i<size;i++)
          {
             System.out.print(hobby[i]+" ");
          }
      }
    }

    public static void main(String[] args) {
        MainHobby hob = new MainHobby();
        hob.printHobby();
    }
}

答案 1 :(得分:0)

您只需在主方法下添加代码行即可在屏幕上打印数组:

的System.out.println(Arrays.toString(爱好);