有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我已经完成了这段代码,它正确地打印了总行数,但对于总字数,它总是打印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);
  }




}

共 (2) 个答案

  1. # 1 楼答案

    scan.next()
    

    返回下一个“单词”

    如果你用一个单词创建一个新的^{,它只会看到一个单词

    这将发生在

    String line = scan.next();
    wordsCounter(new Scanner(line) );
    
  2. # 2 楼答案

    这在我看来相当复杂

    只需将每一行保存在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();
    

    您也不应该忘记调用close()方法来避免资源泄漏