0% found this document useful (0 votes)
25 views2 pages

JAVA Class Activity

The document presents a Java program that reads integers from a file named 'data.txt', calculates their sum, and handles potential errors during file reading and number parsing. It utilizes BufferedReader for file operations and stores the numbers in a list. The program also outputs the numbers read and their total sum to the console.

Uploaded by

mikeyragz6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

JAVA Class Activity

The document presents a Java program that reads integers from a file named 'data.txt', calculates their sum, and handles potential errors during file reading and number parsing. It utilizes BufferedReader for file operations and stores the numbers in a list. The program also outputs the numbers read and their total sum to the console.

Uploaded by

mikeyragz6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INTE/MG/1526/09/22:

Mike Murage.

Java class activity

1.

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ReadDataFromFile {

public static void main(String[] args) {

List<Integer> numbers = new ArrayList<>();

String filePath = "[Link]";

int sum = 0; // Initialize sum variable

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

int lineNumber = 1;

String line;

while ((line = [Link]()) != null) {

try {

int number = [Link]([Link]());

[Link](number);
sum += number; // Add number to the sum

} catch (NumberFormatException e) {

[Link]("Error parsing line " + lineNumber + ": " + line);

lineNumber++;

[Link]("Numbers read from the file:");

for (int number : numbers) {

[Link](number);

[Link]("Sum of the numbers: " + sum);

} catch (FileNotFoundException e) {

[Link]("Error: File '" + filePath + "' not found.");

} catch (IOException e) {

[Link]("Error reading file: " + [Link]());

You might also like