简体   繁体   中英

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.

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 .

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() . 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; but I think it should be l += 1 .

As Robert pointed out, there is an error when counting the line. 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 . 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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