簡體   English   中英

Java,如何使用 .nextLine 作為對象引用

[英]Java, How can I use .nextLine as an object reference

我想使用我掃描的東西作為對不同類中方法的對象的引用。 基本上是scanner.nextLine().method(); 但無論我嘗試什么,我都找不到符號

我正在掃描一個 txt 文件,想為每個新單詞創建一個新的 Word 類,如果這個詞重復,我應該使用 Word 類的方法增加一個計數器。

    class Word{
int counter = 1;

public counterIncrease(){
counter ++;
}
}

我應該掃描單詞,將它們放在一個名為 fileArray 的 ArrayList 中,然后檢查它們是否重復,如果重復,我應該增加 Word 類的計數器,如果不是,我創建一個新的 Word

while(scanner.hasNextLine()){
String temp = scanner.nextLine();
   if(fileArray.contains(temp){
       temp.counterIncrease();
   else{
        fileArray.add(new Word(temp);
       }

你在這里至少有三個問題。 首先,如果你的fileArray是一個List<Word> ,你試圖在一個Word對象列表中找到一個字符串( nextLine()的返回類型nextLine() ......這永遠不會起作用。

其次,您試圖對字符串而不是Word的實例調用counterIncrease()

第三,當我很確定你只想調用一次nextLine()時,你會多次調用它。

我強烈懷疑您想要一個Map<String, Word> ,此時您可以使用:

String line;
while ((line = scanner.nextLine()) != null) {
    Word word = map.get(line);
    if (word === null) {
        map.put(line, new Word(line)); // I assume this constructor exists
    } else {
        word.counterIncrease();
    }
}

此代碼每次迭代僅調用nextLine()一次,按 string查找當前單詞,並且僅對Word的實例調用counterIncrease()

我會親自更改Word代碼,以便counter為 0,直到您調用counterIncrease ,此時循環將變為:

String line;
while ((line = scanner.nextLine()) != null) {
    Word word = map.get(line);
    if (word === null) {
        word = new Word(line);
        map.put(line, word);
    }
    word.counterIncrease();
}

換句話說,您將“確保我們有一個Word實例”與“增加單詞的計數”分開。 誠然,這不是一個巨大的差異......

不清楚你的Word類是否真的有必要的構造函數——它應該是這樣的:

public final class Word {
    private int count;
    private final String text;

    public Word(String text) {
        this.text = text;
    }

    public int getCount() {
        return count;
    }

    public int incrementCount() {
        return ++count;
    }

    public String getText() {
        return text;
    }
}

說了這么多,如果你想要字數,你根本不需要Word類。 您可以只使用Map<String, Integer>Map<String, AtomicInteger> 例如:

Map<String, AtomicInteger> map = new LinkedHashMap<>();

String line;
while ((line = scanner.nextLine()) != null) {
    AtomicInteger counter = map.get(line);
    if (counter === null) {
        counter = new AtomicInteger();
        map.put(line, counter);
    } 
    counter.incrementAndGet();
}
while(scanner.hasNextLine()){
   // you only want to use nexLine() once per while loop, otherwise your scanner goes forward each time
   String line = scanner.nextLine();
   if(fileArray.contains(line){
      //line.increaseCounter(); there is not such a method for String
   else{
        fileArray.add(new Word(line);
       }

暫無
暫無

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

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