Answer to Question #349290 in Java | JSP | JSF for Ail

Question #349290

Create a Java program that asks the user to input a student number. The format of the student number is a sequence of the following:



Four (4) digits


A dash


Two (2) digits


A dash


Three (3) digits


Display a welcome message if the student number is valid; otherwise, show an appropriate error message. Do not copy the welcome message in the sample output.

1
Expert's answer
2022-06-08T14:27:47-0400
import java.util.Scanner;

class Main {
    private static boolean isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    private static boolean isValid(String studentNumber) {
        return studentNumber.length() == 11 &&
                isDigit(studentNumber.charAt(0)) &&
                isDigit(studentNumber.charAt(1)) &&
                isDigit(studentNumber.charAt(2)) &&
                isDigit(studentNumber.charAt(3)) &&
                studentNumber.charAt(4) == '-' &&
                isDigit(studentNumber.charAt(5)) &&
                isDigit(studentNumber.charAt(6)) &&
                studentNumber.charAt(7) == '-' &&
                isDigit(studentNumber.charAt(8)) &&
                isDigit(studentNumber.charAt(9)) &&
                isDigit(studentNumber.charAt(10));
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter a student number: ");
            String studentNumber = scanner.nextLine();
            if (isValid(studentNumber))
                System.out.println("Welcome, student # " + studentNumber);
            else {
                System.out.println("Student number is invalid");
                System.out.println("Valid student number has format XXXX-XX-XXXX (each `X` is a digit)");
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS