KNA-7 InputFromFile
KNA-7 InputFromFile
Java Program to read Numbers from a File and Perform Arithmetic Operations
1. Package Declaration
package UserGiven;
2. Import Statements
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
try {
File file = new File(filePath);
Scanner scanner = new Scanner(file);
if (!scanner.hasNextInt()) {
System.out.println("Error: input.txt is empty or missing numbers!");
scanner.close();
return;
}
int num1 = scanner.nextInt();
if (!scanner.hasNextInt()) {
System.out.println("Error: input.txt does not contain a second
number!");
scanner.close();
return;
}
int num2 = scanner.nextInt();
scanner.close();
7. Performing Calculations
8. Handling Division
if (calculator.num1 != 0) {
System.out.println("Division: " + calculator.div());
} else {
System.out.println("Error: Division by zero is not allowed.");
}
} catch (FileNotFoundException e) {
System.out.println("Error: File not found - " + filePath);
e.printStackTrace();
}
Explanation- Calculator.java