Java problem Open AcctNumsIn.txt and look over the contents. Then open ValidateC
ID: 3837926 • Letter: J
Question
Java problem
Open AcctNumsIn.txt and look over the contents.
Then open ValidateCheckDigits.java and write a program to read in each account number from AcctNumsIn.txt and display whether it is valid.
An account number is valid only if the last digit is equal to the sum of the first five digits divided by 10. For example, the number 223355 is valid because the sum of the first five digits is 15, the remainder when 15 is divided by 10 is 5, and the last digit is 5. Write only valid account numbers to an output file, each on its own line, to a file named AcctNumsOut.txt.
Explanation / Answer
ValidateCheckDigits.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ValidateCheckDigits {
public static void main(String[] args) throws FileNotFoundException {
File outputFile = new File("D:\AcctNumsOut.txt");
PrintWriter output = new PrintWriter(outputFile);
File inputFile = new File("D:\AcctNumsIn.txt");
Scanner scan = new Scanner(inputFile);
while(scan.hasNextInt()){
int accountNum = scan.nextInt();
if(isValidAccountNumber(accountNum)) {
output.write(accountNum+" ");
}
}
output.flush();
output.close();
scan.close();
System.out.println("File AcctNumsOut.txt has been generated");
}
public static boolean isValidAccountNumber(int accountNumber) {
int lastDigit = accountNumber%10;
accountNumber = accountNumber/10;
int sumOfDigits = 0;
while(accountNumber > 0) {
int r = accountNumber % 10;
accountNumber = accountNumber/10;
sumOfDigits = sumOfDigits + r;
}
return lastDigit == sumOfDigits% 10;
}
}
Output:
File AcctNumsOut.txt has been generated
AcctNumsIn.txt
223355
223366
223323
223388
223312
AcctNumsOut.txt
223355
223366
223388
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.