注意:在訪問私有變量:我已經看過其他職位,但我仍然完全迷失了方向。從另一個類
這是我在一個類中的私有變量的代碼:
private int readFile(String fileName)
{
try
{
File f = new File(fileName);
Scanner input = new Scanner(f);
while(input.hasNextLine())
{
String s = input.nextLine();
String[ ] sArr = s.split(" ");
String animal = sArr[ 0 ];
double cost = Double.parseDouble(sArr [ 1 ]);
boolean penNeeded = Boolean.parseBoolean(sArr[ 2 ]);
boolean available = Boolean.parseBoolean(sArr[ 3 ]);
Pet p = new Pet(animal, cost, penNeeded, available);
if (count < animalList.length)
{
animalList[count] = p;
count++;
}
}
input.close();
}
catch(Exception e)
{
System.out.println("Error reading the file:");
System.out.println(e);
e.printStackTrace();
}
return count;
}
我需要訪問它在這片位於另一個類代碼:
static public void processTransaction(String fileName, PettingZoo pz)
{
try
{
// variable should be accessed here
}
catch(Exception e)
{
System.out.println("Error reading the file:");
System.out.println(e);
e.printStackTrace();
}
}
哪有我這樣做?我認爲我需要使用某種修飾符,但我不知道如何實現它。
你可以聲明變量的方法之外,然後創建該變量的getter/setter方法? – Dan
我沒有得到你的問題。我想你想訪問'私人int readFile(字符串文件名)'方法?不是正確的? – Jayamohan
*什麼*「私人變量」?你顯示一個聲明爲「private」的方法......這意味着你不能從另一個類訪問它。 –