63.9k views
5 votes
Using a text editor, create a file that contains a list of at least 15 six-digit account numbers. Read in each account number and display whether it is valid. An account number is valid only if the last digit is equal to the remainder when the sum of the first five digits is 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. Note that the contents of the file AcctNumsIn.txt will change when the test is run to test the program against different input. Grading Write your Java code in the area on the right. Use the Run button to compile and run the code. Clicking the Run Checks button will run pre-configured tests against your code to calculate a grade. Once you are happy with your results, click the Submit button to record your score. AcctNumsIn.txt ValidateCheckDigits.java

User Rajat
by
5.7k points

1 Answer

5 votes

Answer:

See explaination

Step-by-step 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

Using a text editor, create a file that contains a list of at least 15 six-digit account-example-1
Using a text editor, create a file that contains a list of at least 15 six-digit account-example-2
User Ocho
by
5.4k points