簡體   English   中英

可變范圍-JAVA類/方法

[英]Variable Scope - JAVA Class/Method

我正在將數據從文本文件讀入ArrayList,然后嘗試在該ArrayList中搜索特定的字符串(第二種方法)。

我相信我正確地讀取了數據,但是一旦寫滿就很難在ArrayList上實現寫方法。 例如,在下面的檢查方法中,當我確定輸入String在數據結構中時,它將返回false。

我認識到這可能與我的變量范圍有關,或者我的方法如何相互影響(即,當我檢查arraylist時,它實際上並沒有填充數據)。

任何幫助將不勝感激-謝謝

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

public class Word {


ArrayList<String> diclist = new ArrayList<String>();

private void readIn() throws FileNotFoundException {

   File file = new File("filepath");
   Scanner s = new Scanner(file);
   s.useDelimiter("\n");

   while (s.hasNextLine()) {
       diclist.add(s.nextLine());
    }
   s.close();
                                                    }

public boolean checkIn(String z) {//Check if input string z is in diclist

    for (int i = 0; i < diclist.size(); i++) {
        if (diclist.get(i).equals(z)) {return true;}
    }
    return false;
                                                    }
}

到目前為止,您發布的代碼中沒有明顯的問題。 調用readIn ,如果文件存在,可讀且不為空,則應填充列表。 我建議通過調試器運行它。

注意, checkIn方法可以大大簡化為:

return diclist.contains(z);

暫無
暫無

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

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