Java用户输入的字和行计数器

Java用户输入的字和行计数器,java,line,counter,word,Java,Line,Counter,Word,我已经完成了这段代码,它正确地打印了总行数,但对于总字数,它总是打印1个字。谁能帮帮我,谢谢 import java.util.*; public class LineAndWordCounter{ public static void main(String[]args){ Scanner scan = new Scanner(System.in); while(scan.hasNext()){ String line = scan.next();

我已经完成了这段代码,它正确地打印了总行数,但对于总字数,它总是打印1个字。谁能帮帮我,谢谢

import java.util.*;

public class LineAndWordCounter{
  public static void main(String[]args){



    Scanner scan = new Scanner(System.in);
    while(scan.hasNext()){
      String line = scan.next();

      linesCounter(scan);
      wordsCounter(new Scanner(line) );


    }


  }

  public static void linesCounter(Scanner linesInput){
    int lines = 0;
    while(linesInput.hasNextLine()){
      lines++;
      linesInput.nextLine();
    }
    System.out.println("lines: "+lines);
  }

  public static void wordsCounter(Scanner wordInput){
    int words = 0;
    while(wordInput.hasNext()){
      words++;
      wordInput.next();
    }
    System.out.println("Words: "+words);
  }




}
返回下一个“单词”

如果你用一个单词创建一个新的
扫描器,它只能看到一个单词

这将发生在

String line = scan.next();
wordsCounter(new Scanner(line) );

这对我来说相当复杂

您只需将每一行保存在ArrayList中,并将单词累积到变量中即可。 大概是这样的:

List<String> arrayList = new ArrayList<>();
int words = 0;

Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
  String line = scan.nextLine();
  arrayList.add(line);
  words += line.split(" ").length;
  System.out.println("lines: " + arrayList.size());
  System.out.println("words: " + words);
}

scan.close();
List arrayList=new arrayList();
int字=0;
扫描仪扫描=新扫描仪(System.in);
while(scan.hasNext()){
String line=scan.nextLine();
arrayList.add(行);
单词+=行分割(“”)长度;
System.out.println(“行:“+arrayList.size());
System.out.println(“单词:”+单词);
}
scan.close();

你也不应该忘记调用
扫描仪的
close()
方法来避免资源泄漏

你是否应该输入很多行,完成后,计算输入中的行数和字数?@NomadMaker我尝试使用相同的扫描仪来扫描行数和字数,代码将完美地计算行数,但当计算字数时,指针将位于输入的末尾,因此将没有字:(您的函数采用与Scanner相同的参数类型,但您发送了对linesconter和newscanner(line)的扫描)为什么?我认为你应该把同一个扫描对象传递给你的WordsCenter函数,你应该根据空格分割收到的参数。然后你可以计算这一行中的每个单词。目前你只收到一行,并用hasnext()迭代一次@ArdahanKisbet我尝试使用相同的扫描仪来扫描行和字,代码将完美地计算行数,但当计算字数时,指针将位于输入的末尾,因此将没有字。当计算行数时,您将读取整行。您可以使用此字符串(行)并使用String[]words=line.split()。这将为您提供一个数组,数组的长度(words.length)是行中的字数。我找不到通过扫描仪获取所有字数的方法:(因为如果我使用同一个扫描仪进行字数和行数计算,只有其中一个会正确/在不再使用之前不要关闭扫描仪。关闭扫描仪也会关闭为其提供信息的流。如果它是一个文件,这没关系,因为您可以重新打开一个文件。如果它是System.in,则不容易重新打开。when
scan.hasNext()
返回
false
那么扫描仪就不再有用了,不是吗?@Peter Lustig非常感谢!它确实可以工作,只需稍作修改:System.out.println(“行:+arrayList.size());System.out.println(“字:+words”);必须退出while循环以避免每次循环时打印。您也可以使用org.apache.commons.lang中的
line.split(“\\s”)
line.split(StringUtils.SPACE)
。我不建议为此添加额外的依赖项。
List<String> arrayList = new ArrayList<>();
int words = 0;

Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
  String line = scan.nextLine();
  arrayList.add(line);
  words += line.split(" ").length;
  System.out.println("lines: " + arrayList.size());
  System.out.println("words: " + words);
}

scan.close();