Commit 8dbf9736 authored by Bhargavi Ghanta's avatar Bhargavi Ghanta

Task 5 completed: Interactive parser with file input and user-selected operation

parent dbfd8999
40
35
-7
hello
0
200
import java.util.Scanner.*;
import java.util.*;
public class DivisionExample {
......
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileIntegerParser {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Ask for file path
System.out.print("Enter path to the file (e.g., numbers.txt): ");
String filePath = input.nextLine();
ArrayList<Integer> numbers = new ArrayList<>();
try {
File file = new File(filePath);
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
try {
int number = Integer.parseInt(line.trim());
numbers.add(number);
} catch (NumberFormatException e) {
System.out.println("Skipping invalid number format: " + line);
}
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filePath);
return;
}
// Ask for operation
System.out.println("\nChoose an operation:");
System.out.println("1. Sum");
System.out.println("2. Average");
System.out.println("3. Divide each number by a value");
System.out.print("Enter your choice (1/2/3): ");
int choice = input.nextInt();
switch (choice) {
case 1:
int sum = 0;
for (int num : numbers) sum += num;
System.out.println("Sum: " + sum);
break;
case 2:
if (numbers.size() > 0) {
double avg = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println("Average: " + avg);
} else {
System.out.println("No numbers to average.");
}
break;
case 3:
System.out.print("Enter divisor: ");
int divisor = input.nextInt();
if (divisor == 0) {
System.out.println("Cannot divide by zero.");
} else {
for (int num : numbers) {
System.out.println(num + " / " + divisor + " = " + (num / (double) divisor));
}
}
break;
default:
System.out.println("Invalid choice.");
}
input.close();
}
}
10
20
30
40
50
60
70
80
90
\ No newline at end of file
Markdown is supported
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