当用户使用 System.in 输入文本时,我的以下代码无法读取或无限循环。如果我将文本硬编码到 Scanner 变量中,它工作正常,所以我不确定此代码的 System.in 部分有什么问题。任何帮助表示赞赏。
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
最佳答案
正如已经提到的,附加到 System.in 的扫描程序在寻找更多输入时会阻塞。解决此问题的一种方法是从扫描仪中读取一行,对其进行标记,然后以这种方式循环遍历单词。看起来像这样:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
您始终可以用一种循环结构(for、while、do-while)替换另一种循环结构。它们都做同样的事情,只是使用不同的语法,根据情况使一个比其他的使用起来更简单。所以如果你想使用 while 循环,你可以这样做:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
但是,我认为在循环已知数据集的情况下,for 循环更干净。当数据集未知但退出条件已知时,While 循环会更好。
关于Java 扫描器类 (System.in),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60006694/