[英]Fixing an infinite loop when taking a user input in 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.");
}
}
}
}
無限循環是由於line buffer.close() ;
進行調整
刪除buffer.close() ;
//buffer.close() ;
case "3": keep_going=false;break;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.