簡體   English   中英

來自另一個類方法內部的Java訪問數組

[英]Java access array from inside another class method

我需要不使用getter來訪問不同類中的數組。 我有一個傳遞給方法的掃描程序,該方法創建數組,然后調用一個方法以文件中的數據遞歸地填充數組。 然后,我需要訪問toString方法並使用該類(Student []列表)中的數組。

Public class Test
{
public static void main(String[] args) throws IOException
{
 int actual = 0;
File input = new File("input.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
Scanner scan = new Scanner(input);
C155.createList(scan);
actual = C155.getSize();
// writer.write(C155.toString(C155.list, ??????));
writer.close();
}
  }

public class C155 {
public static final int MAXSIZE = 22;
  private static int size = 0;
  public static Student[] createList(Scanner scan)
  {
    Student[] list = new Student[MAXSIZE];
    return populateList(list, scan);
  }
  private static Student[] populateList( Student[] list, Scanner scan )   
  {
    Student s;
    if ( size < MAXSIZE && scan.hasNext() )
     {
      s = new Student(scan.next(), scan.next(),scan.next(),
                      scan.nextDouble(), scan.nextInt());
       list[size] = s;
       size++;
       System.out.println(s);
       return populateList(list, scan);
     }
     else
    return list;
}
public static String toString(Student[] list, int n)
{
    String all= "All Students \n";
    for (int x = 0; x <= n; x++)
    {
        all += list[x].toString() + "\n";
    }
    return all;
}

我需要從Test類調用toString方法(需要Student []列表),但是除了創建get方法之外,我真的不知道最好的方法。

注意,C155類中的所有方法都是靜態的,這可能不是最佳方法。

不過,要回答您的問題,您的方法createList(Scanner scan)的返回類型為Student []。 那就是在您的main方法中獲得對該數組的引用的地方。

Scanner scan = new Scanner(input);
Student[] studentArray = C155.createList(scan); <------
actual = C155.getSize();
writer.write(C155.toString(studentArray, studentArray.length())); <------
writer.close();

如果按方法返回列表,為什么需要訪問列表? 只要這樣做:

Student[] list = C155.createList(scan);
writer.write(C155.toString(list, list.length()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM