Java 数行数字

Java 数行数字,java,string,input,Java,String,Input,我收到了一个任务,我必须编写一个程序来接收输入,就像一个2D数组,然后沿着这行数数单词,然后数数行数 例如: Inky Pinky Blinky Clyde Luigi Mario Bowser 02 12 56 35 24 45 23 14 这应该能说出结果7 9 然而,我的代码似乎没有打印出行的第二个结果,程序只是继续运行。它应该通过计算空格来计算单词,使用hasNextLine来计算行数。如果有人有其他想法,我也愿意接受 public class Duplicat

我收到了一个任务,我必须编写一个程序来接收输入,就像一个2D数组,然后沿着这行数数单词,然后数数行数

例如:

Inky Pinky Blinky Clyde Luigi Mario Bowser

02

12

56

35 

24 

45 

23 

14
这应该能说出结果7 9

然而,我的代码似乎没有打印出行的第二个结果,程序只是继续运行。它应该通过计算空格来计算单词,使用hasNextLine来计算行数。如果有人有其他想法,我也愿意接受

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);
    }
}

你写了l=+1;但是我认为它应该是l+=1。

正如罗伯特指出的,在计算线时有一个错误。但实际上,您还需要检查行是否为空,否则您的计数可能会被打破。所以我稍微修改了你的代码。主要的变化是,当你读第一行的时候,也要计算

此外,我将变量名更改为camelcase,正如java上所建议的那样。你应该遵循这一点

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);
    }
}

你的问题是什么?运行代码时得到什么输出?