Skip to content
Snippets Groups Projects
Commit 35ab0b38 authored by Ngoc Pham's avatar Ngoc Pham
Browse files

Upload New File

parent d8c657d5
Branches
No related merge requests found
import java.io.*;
import java.nio.file.*;
public class ProcessIntegers {
public static void main(String[] args) {
if (args.length != 2 || !args[0].equals("-i")) {
System.err.println("Usage: java ProcessIntegers -i <input-file>");
System.exit(1);
}
String filePath = args[1];
long count = 0;
long total = 0;
long maxValue = Long.MIN_VALUE;
try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
try {
int num = Integer.parseInt(line.trim());
count++;
total += num;
if (num > maxValue) {
maxValue = num;
}
} catch (NumberFormatException e) {
System.err.println("Skipping invalid integer: " + line);
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
System.exit(1);
}
if (count == 0) {
System.err.println("No valid integers found in the file.");
System.exit(1);
}
double average = (double) total / count;
displayResults(count, total, average, maxValue);
}
private static void displayResults(long count, long total, double average, long maxValue) {
System.err.println("Count: " + count);
System.err.println("Total: " + total);
System.err.println("Average: " + average);
System.err.println("Max Value: " + maxValue);
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment