Stop reading input in java without EOF

こ雲淡風輕ζ 提交于 2019-12-10 10:55:22

问题


In this question, how do i stop reading input? My program just keeps running, asking for more input.

public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String src;

    while ((src = br.readLine()) != null) {
        String trgt = br.readLine();
       //do something
        }
    }

回答1:


Like this,

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String src;

while ((src = br.readLine()) != null) {
    StringTokenizer st=new StringTokenizer(src);
    if(!st.hasMoreTokens()) break;
    //YOUR LOGIC GOES HERE 
    }
}



回答2:


Look for a special string for instance END. When trgt equals to "END" then you can break the loop.




回答3:


As said @ihsan kocak you can look for a string like EXIT or QUIT.When you find the string just break the loop.




回答4:


Set a specific word as a reading breaker. For example stop. If the user gives the input stop then the reading process will end. Here is an implementation example of this process:

    public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String src;

    while ((src = br.readLine()) != null && !(src.equals("stop"))) {
        String trgt = src;
       //do something
    }
}


来源:https://stackoverflow.com/questions/45832678/stop-reading-input-in-java-without-eof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!