簡體   English   中英

使用get和set方法在兩個類之間傳遞數組(java)

[英]using get and set methods to pass an array between two classes (java)

在我的類ReadInput中,我讀取了一個文件,該文件包含以空格一一分隔的整數,並將其放入inputArray中。 然后,我想在我的B類中使用inputArray(及其大小),並且嘗試使用get和set方法來做到這一點,但我想我沒有正確使用它們並且無法查明我的錯誤。 有人可以幫忙嗎? 謝謝

import java.io.*;
import java.util.*;

public class ReadInput 
{
        String INPUT_FILE_NAME = "pages.dat"; // filename
        private int [] inputArray;
        private int size;



public ReadInput()
  {
      Scanner fileIn=null;  //(Initialization keeps compiler happy)
      try { // open file
          fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
      } catch (FileNotFoundException e) {
          System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
          System.exit(1);
      } 

      while (fileIn.hasNextLine()) 
        {
            String word = fileIn.next();
            size++;

        }

      inputArray = new int [size];
      //test to see that it gives correct size
      System.out.println(size);

      fileIn.close(); // close file

      try { // open file
          fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
      } catch (FileNotFoundException e) {
          System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
          System.exit(1);
      } 


      int i=0;
      while (fileIn.hasNextLine()) 
        {
            inputArray[i] = fileIn.nextInt();
            i++;
        }

      fileIn.close();
  }

      public  int [] getinputArray()
      {
          return inputArray;
      }

      public  void setinputArray(int [] inputArray)
      {
          this.inputArray = inputArray;
      }

      public  int getSize()

      {
          return size;
      }

      public void setsize(int size)
      {
          this.size = size;
      }
}

public class B 
{

    ReadInput in = new ReadInput();

    int [] inputs;

    public B()
    {

    }


    //this method does not work and gives an error
   public void method()
    {
       System.out.println("in FIFO: " + in.getSize());


      for(int j=0; j< inputs.length; j++)
         System.out.print(inputs[j] + " ");

    }

}

B的構造函數中,您需要調用in.initializeArrays()in.getJobs()

現在, in.getSize()0因為這是ReadInput.size的默認值。 另外, in.getInputArray()將為null因為這是ReadInput.inputArray的默認值。

另外,您可以刪除ReadInput.initializeArrays()ReadInput.getJobs()然后將代碼移到ReadInput的零參數構造函數中,如下所示:

class ReadInput {
    // previous fields: size, inputArray, etc.
    public ReadInput() {
        // code for setting size and populating inputArray from the file
    }
    // other methods: getJobs, etc.
}

如果執行此操作,則應該設置好。 您已經通過ReadInput in = new ReadInput();調用了ReadInput的構造函數ReadInput in = new ReadInput(); 行,因此該行應填充in的數據中。

在B的構造函數中,我看不到您在打電話

in.initializeArrays

要么

setinputArray(int [] inputArray)

在獲取大小之前在任何地方實際設置數組。

暫無
暫無

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

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