java - 在 Java 中获取用户输入时修复无限循环
问题描述
我一直在编写我的第一个 Java 脚本并遇到了一个问题。我不明白为什么当它运行时,程序在第一次运行循环时等待用户输入一些东西,然后处理输入并做出相应的响应,但第二次运行它就卡在了无限循环,无需等待用户输入。作为记录,我确实希望这是一个无限循环,除了如果用户输入“3”程序应该结束。如果在每个案例之后我都写“keep_going = false;” 程序运行,但显然不会继续循环。感谢所有帮助,谢谢!
import java.io.*;
class Choice
{
public static void main (String[] args)
{
String input = "";
Boolean keep_going = true;
while (keep_going)
{
input = "";
System.out.println("Welcome to my program! Would you like to:");
System.out.println("1. Say hi.");
System.out.println("2. Find out my favourite colour.");
System.out.println("3. End the program.");
System.out.println(">");
System.out.print( "> " );
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader buffer = new BufferedReader( isr );
try
{
input = buffer.readLine();
buffer.close() ;
}
catch (IOException e )
{
System.out.println(e);
}
switch (input)
{
case "1": System.out.println("Hi!"); break;
case "2": System.out.println("My favourite colour is blue!"); break;
case "3": return;
default : System.out.println(input + " is not a valid option. Please try again.");
}
}
}
}
解决方案
无限循环是由于线buffer.close() ;
进行此调整
消除
buffer.close() ;
//buffer.close() ;
case "3": keep_going=false;break;
推荐阅读
- c# - 使用 JsonPath 在 JObject 中设置值
- python - Python ARP 扫描器
- c++ - const 引用的内存位置
- r - ggplot2 错误:需要 TRUE/FALSE 的地方缺少值。我不知道
- c - 如何在C中使用大于和小于(>和<)比较浮点数
- c# - 使用 null 属性查询 DefaultIfEmpty 的性能
- variables - GNU Make:为什么调用函数不能用于简单的扩展变量?$1 未展开
- java - 有没有办法在 Kotlin 协程范围内启动可运行文件?
- android - Android Studio中的“dp”和int有什么关系?
- angular - 使用无效数据调用 Query.startAt()。不支持的字段值:自定义对象