Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. /**
  2. Exercise#19
  3. Write a program that would determine if the string inputted by the user is a valid code or not.
  4. Here are the scenarios for you to be a valid code:
  5. 1. a code should have a maximum length of 5.
  6. 2. a code should start with a letter.
  7. 3. a code could contain a digit.
  8. 4. a code should end with an asterisk(*).
  9. Ex. input: aj#kj
  10. invalid code
  11. input: a23k*
  12. valid code
  13. */
  14.  
  15. import java.util.Scanner;
  16. import java.util.regex.Matcher;
  17. import java.util.regex.Pattern;
  18.  
  19. public class Exer19 {
  20.  
  21. public static void main(String args[]) {
  22.  
  23. String regex = "(.)*(\\d)(.)*\\*";
  24. Pattern pattern = Pattern.compile(regex);
  25.  
  26. Scanner reader = new Scanner(System.in);
  27. String input = "TEST";
  28.  
  29. System.out.println("Enter a valid string : ");
  30.  
  31. while (!input.equalsIgnoreCase("EXIT")) {
  32.  
  33. input = reader.nextLine();
  34.  
  35. Matcher matcher = pattern.matcher(input);
  36.  
  37. boolean isMatched = matcher.matches();
  38. if (!isMatched) {
  39. System.out.println("Invalid code");
  40.  
  41. } else {
  42.  
  43. if(input.length()> 5)
  44. {
  45. System.out.println("Invalid code");
  46. }
  47. else if(input.substring(0,1).matches("[0-9]"))
  48. {
  49. System.out.println("Invalid code");
  50.  
  51. }
  52. else
  53. {
  54. System.out.println("Valid code");
  55. }
  56. }
  57. }
  58.  
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement