A useful technique for catching typing errors is to use a check digit. For example, suppose that a school assigns a six-digit number to each student. A seventh digit can be determined from the other digits with the use of the following formula:
7th digit = (1 * (1st digit) + 2 * (2nd digit) + . . . + 6 * (6th digit)) % 10
When a user types in a student number, the user types all seven digits. If the number is typed incorrectly, the check digit will fail to match in 90% of the cases. Write an interactive program that prompts for a six-digit student number and reports the check digit for that number, using the preceding formula.
PROGRAM CODE:
//Header file section
import java.util.Scanner;
//Main class name,CheckDigitCalculatorDemo
public class CheckDigitCalculatorDemo
{
public static void main(String[] args)
{
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt for and read the six-digit student number
System.out.print("Enter the six-digit student number: ");
String studentNumber = scanner.next();
// Check if the input has exactly six digits
if (studentNumber.length() != 6 || !studentNumber.matches("\\d+"))
{
System.out.println("Invalid input. Please enter a six-digit number.");
System.exit(1);
}
// Convert the input to an integer array for each digit
int[] digits = new int[6];
for (int i = 0; i < 6; i++)
{
digits[i] = Integer.parseInt(Character.toString(studentNumber.charAt(i)));
}
// Calculate the check digit using the formula
int checkDigit = calculateCheckDigit(digits);
// Output the check digit
System.out.println("Check Digit: " + checkDigit);
}
// Method to calculate the check digit using the given formula
private static int calculateCheckDigit(int[] digits)
{
int sum = 0;
// Calculate the sum of products of each digit with its corresponding position
for (int i = 0; i < 6; i++)
{
sum += (i + 1) * digits[i];
}
// Calculate the check digit using the modulo operation
return sum % 10;
}
}
OUTPUT:
Enter the six-digit student number: 123456
Check Digit: 4