Advertisement
Guest User

02. Song Encryption

a guest
Apr 4th, 2020
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package ExamPrep;
  2.  
  3. import java.util.Scanner;
  4. import java.util.regex.Pattern;
  5.  
  6. public class SongEncryption {
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.         String line = scanner.nextLine();
  11.         while (!"end".equals(line)) {
  12.             String[] token = line.split(":");
  13.             String artist = token[0];
  14.             String song = token[1];
  15.             if (isValidArtist(artist) && isValidSong(song)) {
  16.                 int key = artist.length() % ('z' - 'a' + 1);
  17.                 String enArtist = encrypt(artist, key);
  18.                 String enSong = encrypt(song, key);
  19.                 System.out.printf("Successful encryption: %s@%s%n", enArtist, enSong);
  20.             } else {
  21.                 System.out.println("Invalid input!");
  22.             }
  23.             line = scanner.nextLine();
  24.         }
  25.  
  26.     }
  27.  
  28.     private static String encrypt(String artist, int key) {
  29.         StringBuilder sb = new StringBuilder();
  30.         for (int i = 0; i < artist.length(); i++) {
  31.             char ch = artist.charAt(i);
  32.             char encryptCh;
  33.             if (ch == ' ' || ch == '\'') {
  34.                 encryptCh = ch;
  35.             } else {
  36.                 encryptCh = (char) (ch + key);
  37.                 if (Character.isUpperCase(ch) && encryptCh > 'Z') {
  38.                     encryptCh = (char) ('A' + (encryptCh - 'Z' - 1));
  39.                 }
  40.                 if (Character.isLowerCase(ch) && encryptCh > 'z') {
  41.                     encryptCh = (char) ('a' + (encryptCh - 'z' - 1));
  42.                 }
  43.             }
  44.             sb.append(encryptCh);
  45.         }
  46.         return sb.toString();
  47.     }
  48.  
  49.  
  50.     private static boolean isValidSong(String song) {
  51.         return Pattern.compile("([A-Z ]+)").matcher(song).matches();
  52.     }
  53.  
  54.     private static boolean isValidArtist(String artist) {
  55.         return Pattern.compile("([A-Z][a-z ']+)").matcher(artist).matches();
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement