如何将在另一个方法中创建的 ArrayList 传递到 main 方法以供进一步使用?

问题描述 投票:0回答:1

我正在尝试练习使用 ArrayLists 并创建一个自定义对象类来完成它。尝试找出一种通过单独的方法创建数组列表的方法,然后将其返回到 main 方法以供稍后在程序中使用。

// Imports ArrayLists, Scanner class, Date objects, and try/catch exceptions
import java.util.*;
// Import the File class, FileWriter class, and IOExceptions
import java.io.*;

/**
*  The program will simulate a class registry system
*  Using multiple methods, the program will intake user input to edit the registry
*  After the user is done, the program will ask if the user would like to save the registry to a separate txt file.
*  If ordered to save, the program will then print the path to find the txt file.
*/

public class StudentsMainMeth {
   public static void main(String[] args) throws StudentException {
   
      System.out.println("These are the students currently enrolled:");
      createRoster();
      
      System.out.println("\n\t\t\t**Enrolled Students**");
      for(int i = 0; i < classRoster.size(); i++) {
      
         System.out.println(classRosteer.get(i));
         
      }
   }
   /**
    * Creates the ArrayList "classRoster" to store the custome objects from the Student class
    * The class will use three instance variables
    *    name
    *    grade
    *    gpa
    * the array will add five objects to start and return the ArrayList to the main method
    */
   public static ArrayList<Student> createRoster () throws StudentException {
   
      ArrayList<Student> classRoster = new ArrayList<>();
      classRoster.add(new Student(Aang, 12, 3.5));
      classRoster.add(new Student("Katara", 12, 4.0));
      classRoster.add(new Student("Soka", 12, 4.0));
      classRoster.add(new Student("Toph B.", 1, 4.0));
      classRoster.add(new Student("Zuko", 8));
      return(classRoster);
      
   }
}

尝试编译时,出现错误,指出数组列表未识别为可用符号。

StudentsMainMeth.java:25: error: cannot find symbol
      for(int i = 0; i < classRoster.size(); i++) {
                         ^
  symbol:   variable classRoster
  location: class StudentsMainMeth
StudentsMainMeth.java:27: error: cannot find symbol
         System.out.println(classRosteer.get(i));
                            ^
  symbol:   variable classRosteer
  location: class StudentsMainMeth
2 errors

我是否缺少一些可以在返回 arraylist 时将其识别到 main 方法的内容,或者您是否需要在 main 方法中创建 arraylist 以便确认以供以后使用?

我知道您可以让程序在方法返回数组列表后直接打印数组列表,但重点是在单独的方法中创建后能够在主方法中使用它。我之前已经在一个单独的程序中完成了此操作,但采用从一种方法到另一种方法来传递创建的数组列表,但是如何将它传递到主方法并且稍后仍然可用?

java arraylist methods
1个回答
0
投票

它打印变量未定义。然后你应该创建一个类变量:

public class StudentsMainMeth {
  private List<Student> classRoster = createRoster():
 // The main method and other stuff 
 ...
© www.soinside.com 2019 - 2024. All rights reserved.