繁体   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