[英]Java Scanner Class ( System.in)
当用户使用 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
在程序运行时始终可用,除非您关闭它。 它永远不会退出 while 循环。 所以你可以添加else if (word.equals("exit")) { break; }
else if (word.equals("exit")) { break; }
. 这样,无论何时键入“exit”,它都会关闭 while 循环并在 while 循环之后执行代码。
如前所述,附加到 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 循环会更好。
视情况而定,您是否只想阅读 1 行文本,然后单独计算单词?
因为您只需要一行,所以您可以使用 Scanner 库获取输入字符串并将字符串拆分为单个单词,然后应用 if 语句。 就像是:
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;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.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);
}
这样你就不需要 while 循环了。 所以它的处理器和内存效率更高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.