简体   繁体   English

计数行和字

[英]Counting lines and words

I've received an assignment, where I have to write a program that receives an input, which is like a 2D array, and count the words along the line, and count the amount of lines. 我收到了一个作业,其中我必须编写一个程序来接收输入,就像一个2D数组,并计算沿线的单词,并计算线的数量。

For example: 例如:

Inky Pinky Blinky Clyde Luigi Mario Bowser

02

12

56

35 

24 

45 

23 

14

This should spit out the result 7 9 . 这应该吐出结果7 9

However my code doesn't seem to print out the second result for the lines, the program just keeps on running. 但是我的代码似乎并没有打印出第二行的结果,该程序只是继续运行。 It is supposed to count the words by counting the spaces, and the lines by using hasNextLine() . 应该通过计算空格来计数单词,并通过使用hasNextLine()hasNextLine()行数。 I'm also open for other ideas if anyone has any. 如果有人有其他想法,我也会开放。

public class Duplicate {

    String Sentence;
    String Store[];

    public String getString(Scanner s) {
        Sentence = s.nextLine();

        return Sentence;
    }

    public void count() {

        Store = Sentence.split(" ");
        System.out.print(Store.length + " ");
    }

    public void countLine(Scanner s) {
        int l = 0;
        while (s.hasNextLine()) {
            l = +1;
            s.nextLine();
        }

        System.out.print(l);
    }
}

You wrote l =+ 1; 您写了l =+ 1; but I think it should be l += 1 . 但我认为应该是l += 1

As Robert pointed out, there is an error when counting the line. 正如罗伯特(Robert)指出的那样,计算行数时有错误。 But actually, you need to check also if the line is empty, otherwise your count might be broken. 但是实际上,您还需要检查行是否为空,否则计数可能会被破坏。 So I changed your code a little bit. 因此,我对您的代码做了一些更改。 The main change was around also count when you read the first line. 当您阅读第一行时,主要的变化是也计算在内。

Also, I change the variable names to camelcase, as suggested on the java conventions . 另外,我将变量名更改为camelcase,如Java 约定所建议。 You should follow that. 你应该遵循。

public class Duplicate {

    private String sentence;
    private String store[];
    private int countLines = 0;

    public String getString(Scanner s) {
        sentence = s.nextLine();
        countLines++;
        return sentence;
    }

    public void count() {
        store = sentence.split(" ");
        System.out.print(store.length + " ");
    }

    public void countLine(Scanner s) {
        while (s.hasNextLine()) {
            String line = s.nextLine();

            //verify if line is not empty
            if (!line.isEmpty())
                countLines +=1;
        }

        System.out.print(countLines);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM