java - Java 扫描程序类 (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; }
. 这样,每当您键入“退出”时,它都会关闭 while 循环并在 while 循环之后执行代码。
推荐阅读
- angular - TypeError:child.send 不是函数
- sql-server - 错误数据库中的 SQL Server 表
- java - 将数据加载到 Java GUI
- anylogic - AnyLogic:了解哪个代理在状态图中发送了消息
- angular - 在Angular 6中导航到子路由器出口
- c++ - 为什么我的按钮类项共享相同的 lambda 函数?
- flutter - Flutter - Make a slide pannel looking like a Drawer
- javascript - 未定义 React 调度删除操作
- php - 如何在数据库表中存储多个复选框值
- excel - 使用宏从文本文件导入