BufferedReader and StringTokenizer
The StringTokenizer
class in java.util
can be used to parse a line of integers. Here is a Java program that reads a line of integers, displays each integer, and then calculates and displays the sum of all the integers.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class IntegerProcessor {
public static void main(String[] args) {
BufferedReader reader = null;
try {
// Read input from the console
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a line of integers separated by spaces:");
String line = reader.readLine();
// Use StringTokenizer to parse the line of integers
StringTokenizer tokenizer = new StringTokenizer(line);
int sum = 0;
System.out.println("The integers are:");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
int number = Integer.parseInt(token);
System.out.println(number);
sum += number;
}
// Display the sum of all integers
System.out.println("The sum of all integers is: " + sum);
} catch (IOException e) {
System.err.println("An IOException occurred: " + e.getMessage());
} finally {
// Close the BufferedReader
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Failed to close BufferedReader: " + e.getMessage());
}
}
}
}
}
Explanation:
- BufferedReader: Used to read a line of input from the console.
- StringTokenizer: Used to parse the line of integers separated by spaces.
- Parsing and Processing: The
StringTokenizer
splits the input line into tokens (integers). Each token is parsed to an integer, printed, and added to the sum. - Exception Handling: Handles
IOException
that might occur during reading. - Finally Block: Ensures that the
BufferedReader
is closed properly.
Detailed Steps:
Reading Input:
- The program reads a line of integers from the console using
BufferedReader
.
- The program reads a line of integers from the console using
Using
StringTokenizer
:- The
StringTokenizer
object is created with the input line. - The
while
loop iterates through each token, converts it to an integer, prints it, and adds it to the sum.
- The
Displaying Results:
- After processing all tokens, the program prints the sum of all integers.
Exception Handling:
- The try block handles the input operations and catches any
IOException
. - The finally block ensures that the
BufferedReader
is closed properly to release the resources.
Programs to Try:
Find the sum of even and odd integers separately
Comments
Post a Comment