[英]Counting number of words and characters from several lines of user input
描述: “编写一个程序来从 Scanner 读取几行文本(每行以 '.' 结尾)。它应该计算单词的数量和非空格字符的数量。程序在读取时应该停止接受输入单独的输入行中的单词 (DONE)。”
我遇到了这个程序的问题。 每当我输入示例文本并输入 DONE 时,单词和字符的数量仅与“DONE”这个词匹配。 如果有人可以提供一个有效的修复程序,那将非常有助于我理解手头的问题。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter text (type DONE to quit): ");
String text = "";
while (!"DONE".equals(text)) {
text = input.next();
}
String[] numOfWords = text.split(" ");
String[] numOfChars = text.split("");
System.out.print("Number of words: " + numOfWords.length);
System.out.println("");
System.out.print("Number of non-space characters: " + numOfChars.length);
}
}
由于上面的答案不正确(无法编译或工作),您可以尝试以下操作:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter text (type DONE to quit): ");
String text = "";
String output = "";
while (!"DONE".equals(text)) {
text = input.next();
output += text.replace("DONE", "") + " ";
}
String[] numOfWords = output.split(" ");
String[] numOfChars = output.split("");
System.out.print("Number of words: " + numOfWords.length);
System.out.println("");
System.out.print("Number of non-space characters: " + numOfChars.length);
}
有效地为输入字符串创建另一个存储,一旦提供了 DONE 关键字,在删除单词“DONE”后退出循环。
在您的代码中发生的情况是,最后您输入的是 DONE,因此它只计算完成,使用以下代码
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter text (type DONE to quit): ");
String text = "";
while (true) {
if(!text.equals("DONE")){
break;
}
text += " " + input.nextLine();
}
String[] numOfWords = text.split(" ");
String[] numOfChars = text.split("");
System.out.print("Number of words: " + numOfWords.length);
System.out.println("");
System.out.print("Number of non-space characters: " +
numOfChars.length);
}
}
其他两个答案都无法解决计算字符数的错误。 以下代码正确解释了缺少空格的情况,去掉了输入终止文本,并正确计算了非空格字符:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter text (type DONE to quit): ");
String text = "";
String output = "";
while (!"DONE".equals(text)) {
text = input.next();
output += text.replace("DONE", "") + " ";
}
String[] numOfWords = output.split(" ");
int numOfChars = output.replace(" ", "").length();
System.out.print("Number of words: " + numOfWords.length);
System.out.println("");
System.out.print("Number of non-space characters: " + numOfChars);
}
}
输入:包含四个单词的文本完成
输出
请输入文本(键入 DONE 退出):
字数:4
非空格字符数:17
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.