gpt4 book ai didi

java - 计算行数和单词数

转载 作者:太空宇宙 更新时间:2023-11-04 13:57:14 25 4
gpt4 key购买 nike

我收到了一项作业,其中我必须编写一个程序来接收输入(就像一个二维数组),并计算沿行的单词数,并计算行数。

例如:

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

最佳答案

正如 Robert 指出的,计算行数时出现错误。但实际上,您还需要检查该行是否为空,否则您的计数可能会被破坏。所以我稍微改变了你的代码。主要的变化是当您阅读第一行时也进行计数。

此外,我将变量名称更改为驼峰式,如 java conventions 上的建议。 。你应该遵循这一点。

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

关于java - 计算行数和单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29695065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com