![](/img/trans.png)
[英]Why can't I access my int array values that I made in my main method from another method? (beginner Java coder)
[英]Why I can't show my list from another method?
你能告訴我為什么當我嘗試從其他方法啟動它時看不到我的列表嗎? 以下方法:
public class CollectionsOperation {
private List<Client> bufferedReaderClientLIst = new ArrayList<Client>();
private List<Client> emptyBoxForCf = new ArrayList<Client>();
BufferedReader bf = null;
private static final String fileName = "Clients.txt";
public List<Client> bufferedReaderCollection() throws IOException {
String line;
bf = new BufferedReader(new InputStreamReader (new FileInputStream(fileName), "UTF-8"));
while((line = bf.readLine()) != null) {
String[] split = line.split(";");
String nameCompany = split[0].substring(2);
String adress = split[1];
String phoneNumber = split[2];
String emailAdress = split[3];
Client k = new Client(nameCompany, adress, phoneNumber, emailAdress);
bufferedReaderClientLIst.add(k);
}
System.out.println(bufferedReaderClientLIst);
return bufferedReaderClientLIst;
}
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
調用方法:
public static void main(String[] args) throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.show();
}
這就是我得到的結果:
[ MarkCompany';Ilusiana';0982882902';mark@company.com, CorporationX';Berlin';93983';X@Corporation.com]
[]
為什么第二個列表是空的? 方法bufferedReaderCollection()
返回一個結果,並且列表bufferedReaderClientLIst
可用於所有方法。 怎么了?
在show()
:
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
您創建另一個CollectionsOperation
對象來調用bufferedReaderCollection()
。 這是不必要的。
但是,問題出在您打印bufferedReaderClientList
的最后一個打印語句中。 這是打印this
實例的bufferedReaderClientList
,而不是k
。 因為您沒有在this
上調用bufferedReaderCollection
,所以列表將為空,因此[]
打印在最后。
而不是創建另一個實例,使用this
:
public void show() throws IOException {
this.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.