Input loop: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created task with Java)
 
m (→‎{{header|Java}}: Fixed up the exception handling area)
Line 25: Line 25:
//process the input here
//process the input here
}
}
} catch (IOException e) {
} catch (IOException e) {
//There was an input error
// TODO Auto-generated catch block
}
e.printStackTrace();
}

Revision as of 03:49, 18 February 2008

Task
Input loop
You are encouraged to solve this task according to the task description, using any language you may know.

Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.

Java

Some people prefer Scanner or BufferedReader, so a way with each is presented.

import java.util.Scanner;
...
Scanner in = new Scanner(System.in);//stdin
//new Scanner(new FileInputStream(filename)) for a file
//new Scanner(socket.getInputStream()) for a network stream
while(in.hasNext()){
	String input = in.next(); //in.nextLine() for line-by-line
	//process the input here
}

or

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
...
try{
	BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));//stdin
	//new BufferedReader(new FileReader(filename)) for a file
	//new BufferedReader(new InputStreamReader(socket.getInputStream())) for a netowrk stream
		while(inp.ready()){
			String input = inp.readLine();//line-by-line only
			//process the input here
		}
} catch (IOException e) {
	//There was an input error
}