[英]Counting lines and words
我收到了一个作业,其中我必须编写一个程序来接收输入,就像一个2D数组,并计算沿线的单词,并计算线的数量。
例如:
Inky Pinky Blinky Clyde Luigi Mario Bowser
02
12
56
35
24
45
23
14
这应该吐出结果7 9
。
但是我的代码似乎并没有打印出第二行的结果,该程序只是继续运行。 应该通过计算空格来计数单词,并通过使用hasNextLine()
来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
。
正如罗伯特(Robert)指出的那样,计算行数时有错误。 但是实际上,您还需要检查行是否为空,否则计数可能会被破坏。 因此,我对您的代码做了一些更改。 当您阅读第一行时,主要的变化是也计算在内。
另外,我将变量名更改为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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.