首页 > 解决方案 > 如何在 JAVA 中从一种方法访问对象数组到另一种方法?

问题描述

我创建了一个对象数组,该数组是从此处名为 dataInput() 的方法创建的。我想在 main 方法中调用 people 数组。提前致谢。

public static void dataInput() {

    Scanner input = new Scanner(System.in);

    int noOfPersons = 3;

    String name = "";
    int no = 0;
    String city = "";

    inputTry[] persons = new inputTry[3];
    persons[0] = new inputTry(name, no, city);
    persons[1] = new inputTry(name, no, city);
    persons[2] = new inputTry(name, no, city);

    for (int i = 0; i < noOfPersons; i++) {
        System.out.print("Enter person name: ");
        name = input.nextLine();
        System.out.print("Enter person number: ");
        no = input.nextInt();
        input.nextLine();
        System.out.print("Enter where the person lives: ");
        city = input.nextLine();

        persons[i].name = name;
        persons[i].no = no;
        persons[i].city = city;
    }
}

标签: javaclassoopmethods

解决方案


  • 如果dataInput()main
    的同一类中, 您可以在“类的开头”声明这个数组全局。

  • 如果dataInput()不在main
    类中, 您可以创建一个名为 example 的公共方法,getPersonsArray() 并从dataInput(). 现在您可以从此类中获取对象并调用方法getPersonsArray()


  public static void dataInput() {
     // your code
     inputTry[] persons = new inputTry[3];
     getPersonsArray(name, no, city);
    // your code
  }

    public static inputTry[] getPersonsArray(String name,int no,String city) {
       persons[0] = new inputTry(name, no, city);
       persons[1] = new inputTry(name, no, city);
       persons[2] = new inputTry(name, no, city);

       return persons;
    }

推荐阅读