【发布时间】:2020-01-31 15:20:48
【问题描述】:
当用户使用 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);
}
}
【问题讨论】:
-
另外,能否请您正确格式化您的代码,如果有任何缩进更容易理解或查看错误。
-
对不起,它应该打印计数,但它只是无限循环而不打印字数。如果我对 Scanner 变量中的文本进行硬编码,它会给我准确的计数,因此 System.in 无法正常工作
-
用户是否希望输入一个扫描仪会破解并计数的句子?
-
Sree,是的,就是这个想法。