Parsing with Scanner and InputStreamReader/BufferReader

Hello everyone!

I’m new to the community and I’m happy to be here. :slight_smile: I am a beginner in Java and I was trying out the ATM problem on the Easy problems.

I completed the program and I wanted to enhance it. I noticed that the problem had two integers on the first line, and I thought of creating a program that parses multiple inputs on a single line. I created a program that used InputStreamReader as an object for BufferReader to do this task as shown below. Right now, the program does something with only the first two elements of the integer array, which is fine.

I want to accomplish the same thing using Scanner if possible. I honestly haven’t used the Scanner object because I don’t know how to parse the string without bringing it into BufferReader. I was wondering if there was a way to parse multiple inputs using a Scanner instead of InputStreamReader and BufferReader.


public class Testing {

public static void main(String[] args) throws IOException{

	InputStreamReader input = new InputStreamReader(System.in); 
	BufferedReader br = new BufferedReader(input);

	String line = br.readLine(); // this sets the input = to a string
	String[] parsed = line.trim().split("\\s+");
	double[] bNums = new double[parsed.length]; 

	for (int i = 0; i < parsed.length; i++) {
		bNums[i] = Integer.parseInt(prsed[i]);
	}

		if ((0 <= bNums[1]) && (bNums[1] <= 2000)) {

			if ((0 < bNums[0]) && (bNums[0] <= 2000) && (bNums[0] % 5 == 0)
					&& (bNums[1] > (bNums[0] + .5))) {
				bNums[1] = bNums[1] - bNums[0] - .5;
			}
		} // end of nested if statement

		System.out.printf("%.2f", bNums[1]);
	
}

}


HI,

Using scanner in java is much faster than BufferedReader. Scanner consists of inbuilt tokenezers where buffered reader does not. More over BufferedReader is preferred in serialization and data transfer as far as my knowledge.
//sample usage of scanner
Scanner sr=new Scanner(System.in);
String s=sr.nextLine();
//now apply whatever operations you need.