首页 > 解决方案 > 在 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.");
        }
    }


} 

}

标签: javaloopsvalidationinputinfinite-loop

解决方案


无限循环是由于线buffer.close() ;

进行此调整

  1. 消除buffer.close() ;

    //buffer.close() ;

  2. case "3": keep_going=false;break;


推荐阅读