问题
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