Java方法不起作用,导致程序挂起

时间:2015-03-19 19:58:00

标签: java class methods

您好我正在编写一个程序来分析文本块,特别是读取文件并计算该文件中的行数,字数和数字。

我已经尝试在一个方法中计算一个单独的类中的行数,然后尝试在主类中调用该方法来打印文件中的总行数,但这不会像我预期的那样工作并导致我尝试调用行计数方法时挂起的程序。非常感谢任何帮助!

主类:

package cw;

import java.util.Scanner;

public class TextAnalyser {

    public static void main(String[] args) {
        LineCounter object = new LineCounter();

        Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
        int totalNumbers = 0;
        int totalDigits = 0;
        int totalWordCount = 0;
        int totalLines = 0;

        while (sc.hasNext()) {
            totalWordCount++;

            if (sc.hasNextInt()) {
                totalDigits += sc.nextInt();
                totalNumbers++;
            }
            else {
                sc.next();
            }
        }

        System.out.println("The total of all digits added = " + totalDigits);
        System.out.println("The total number of digits in the file = " + totalNumbers);
        System.out.println("The total number of words in the file = " + totalWordCount);
        object.TotalLines();
    }
}

行计数类:

package cw;
import java.util.Scanner;
//Class that counts the lines in a file.
public class LineCounter {
    public static void TotalLines() {
        Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
        System.out.println("hi");
        int linetotal = 0;
        while (sc.hasNextLine()) {
            linetotal++;
        }

        System.out.println(linetotal);
    }
}

2 个答案:

答案 0 :(得分:2)

hasNextLine()仅告诉您如果有下一行 - 它不会读取它。所以你站在起点并问'下一行是否有?"一次又一次......你应该尝试通过nextLine();

实际读取它

答案 1 :(得分:0)

just addline of code

while(sc.hasNextLine()){
          String sentence = sc.nextLine();
          linetotal++;
      }

在您的public static void TotalLines(){方法中......

这样{。{1}},actually get the next line询问 not only中是否存在另一行while返回always并且true退出while循环!)