![](/img/trans.png)
[英]Can not Pass Selenium WebDrivers between two classes using Java on Eclipse
[英]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.