Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ExamPrep;
- import java.util.Scanner;
- import java.util.regex.Pattern;
- public class SongEncryption {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String line = scanner.nextLine();
- while (!"end".equals(line)) {
- String[] token = line.split(":");
- String artist = token[0];
- String song = token[1];
- if (isValidArtist(artist) && isValidSong(song)) {
- int key = artist.length() % ('z' - 'a' + 1);
- String enArtist = encrypt(artist, key);
- String enSong = encrypt(song, key);
- System.out.printf("Successful encryption: %s@%s%n", enArtist, enSong);
- } else {
- System.out.println("Invalid input!");
- }
- line = scanner.nextLine();
- }
- }
- private static String encrypt(String artist, int key) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < artist.length(); i++) {
- char ch = artist.charAt(i);
- char encryptCh;
- if (ch == ' ' || ch == '\'') {
- encryptCh = ch;
- } else {
- encryptCh = (char) (ch + key);
- if (Character.isUpperCase(ch) && encryptCh > 'Z') {
- encryptCh = (char) ('A' + (encryptCh - 'Z' - 1));
- }
- if (Character.isLowerCase(ch) && encryptCh > 'z') {
- encryptCh = (char) ('a' + (encryptCh - 'z' - 1));
- }
- }
- sb.append(encryptCh);
- }
- return sb.toString();
- }
- private static boolean isValidSong(String song) {
- return Pattern.compile("([A-Z ]+)").matcher(song).matches();
- }
- private static boolean isValidArtist(String artist) {
- return Pattern.compile("([A-Z][a-z ']+)").matcher(artist).matches();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement