Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Exercise#19
- Write a program that would determine if the string inputted by the user is a valid code or not.
- Here are the scenarios for you to be a valid code:
- 1. a code should have a maximum length of 5.
- 2. a code should start with a letter.
- 3. a code could contain a digit.
- 4. a code should end with an asterisk(*).
- Ex. input: aj#kj
- invalid code
- input: a23k*
- valid code
- */
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Exer19 {
- public static void main(String args[]) {
- String regex = "(.)*(\\d)(.)*\\*";
- Pattern pattern = Pattern.compile(regex);
- Scanner reader = new Scanner(System.in);
- String input = "TEST";
- System.out.println("Enter a valid string : ");
- while (!input.equalsIgnoreCase("EXIT")) {
- input = reader.nextLine();
- Matcher matcher = pattern.matcher(input);
- boolean isMatched = matcher.matches();
- if (!isMatched) {
- System.out.println("Invalid code");
- } else {
- if(input.length()> 5)
- {
- System.out.println("Invalid code");
- }
- else if(input.substring(0,1).matches("[0-9]"))
- {
- System.out.println("Invalid code");
- }
- else
- {
- System.out.println("Valid code");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement