utkarsh691-sopho
utkarsh691-sopho

Reputation: 47

Stop reading input in java without EOF

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
        }
    }

Upvotes: 2

Views: 1521

Answers (4)

Anastasios Vlasopoulos
Anastasios Vlasopoulos

Reputation: 1802

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
    }
}

Upvotes: 0

Rakesh
Rakesh

Reputation: 466

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 
    }
}

Upvotes: 2

Niranjan  Nayak
Niranjan Nayak

Reputation: 89

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

Upvotes: 0

ihsan kocak
ihsan kocak

Reputation: 1581

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

Upvotes: 0

Related Questions