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.
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)");
}
}
}
}
Comments
Leave a comment