Answer:
See explaination
Explanation:
/File: ValidateCheckDigits.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ValidateCheckDigits {
public static void main(String[] args) {
String fileName = "numbers.txt"; //input file name
String validFileName = "valid_numbers.txt"; // file name of the output file
//Open the input file for reading and output file for writing
try(Scanner fileScanner = new Scanner( new File(fileName));
BufferedWriter fileWriter = new BufferedWriter( new FileWriter(validFileName))) {
//Until we have lines to be read in the input file
while(fileScanner.hasNextLine()) {
//Read each line
String line = fileScanner.nextLine().trim();
//calculate the sum of first 5 digits
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += Integer.parseInt( line.charAt(i) + "");
}
//Get the last digit
int lastDigit = Integer.parseInt(line.charAt(5)+"");
//Check if the remainder of the sum when divided by 10 is equal to last digit
if(sum%10 == lastDigit) {
//write the number in each line
fileWriter.write(line);
fileWriter.newLine();
System.out.println("Writing valid number to file: " + line);
}
}
System.out.println("Verifying valid numbers completed.");
} catch(IOException ex ) {
System.err.println("Error: Unable to read or write to the file. Check if the input file exists in the same directory.");
}
}
}
Check attachment for output and screenshot