我一直在写我的第一个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.");
}
}
}
}
答案 0 :(得分:0)
无限循环归因于buffer.close() ;
行
进行此调整
删除buffer.close() ;
//buffer.close() ;
case "3": keep_going=false;break;