-1
public static boolean EncrptionKey(String Key) {
        Scanner input = new Scanner(System.in);
        Key = input.next();
        
        if(Key.matches("^[a-zA-Z]") && Key.length()==26) {
            System.out.println("True");
            return true;
        }
        System.out.println("False");
        return false;
        
    }

This code is to check whether the user has entered a correct encryption key for a message to be encrypted. So they have to enter a key which is either a-z or A-Z, has to be 26 letters long and cannot have any repeating characters so that a message can be encrypted.

logi-kal
  • 7,107
  • 6
  • 31
  • 43
Rush
  • 1
  • 1
    Your regular expression only matches a string that is one character long. Hence your `if` condition will **never** be true. Maybe try `Key.matches("^[a-zA-Z]+") && Key.length()==26` – Abra May 22 '21 at 13:04
  • What if i wanted to used a for loop to check each character for duplicates? Or something a little simpler as i have not learned how to use sets/ – Rush May 22 '21 at 14:22
  • Does _repeating characters_ mean the same letter cannot appear consecutively, for example `hh`, or does it mean that each letter in the key can only appear in the key once only? – Abra May 22 '21 at 14:30
  • An example key is abcdefghijklmnopqrstuvwxyz, meaning each letter in the alphabet can only appear once in the key, if a letter is repeated like aabcdefghijklmnopqrstuvwxyzz then it should be false. – Rush May 22 '21 at 14:35
  • Is `AbcdefghijklmnopqrstuvwxyA` a valid key? – Abra May 22 '21 at 14:39
  • No because A is repeated, the key can only have one of each letter. – Rush May 22 '21 at 14:48
  • Are `a` and `A` considered to be the same letter? In other words, is `abcdefghijklmnopqrstuvwxyA` a valid key? – Abra May 22 '21 at 15:07
  • Yes but now I'm realising I'm not sure how to code that using regex, to make it so that the letters aren't repeated and are all uppercase. – Rush May 22 '21 at 15:09
  • Oh wait sorry this is not a valid key --> abcdefghijklmnopqrstuvwxyA – Rush May 22 '21 at 16:20

3 Answers3

0

You use the wrong regex. Use "^[a-zA-Z]+"

Also, to check if there are duplicate chars we can add all chars to a Set then see if its size is the same (it means no duplicate chars).

You can do:

public static boolean EncrptionKey() {
    Scanner input = new Scanner(System.in);
    String Key = input.next();

    Set<Character> characterSet = Key.chars()
            .mapToObj(c -> (char) c).map(c -> c.toString().toLowerCase().toCharArray()[0]) 
            .collect(Collectors.toSet());
    if(Key.matches("^[a-zA-Z]+") && Key.length()==26 && characterSet.size() == Key.toCharArray().length) {
        System.out.println("True");
        return true;
    }
    System.out.println("False");
    return false;

}

Note: if 'A' and 'a' are not duplicates, use this:

Set<Character> characterSet = Key.chars()
         .mapToObj(c -> (char) c)
         .collect(Collectors.toSet());
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
0

I would suggest you not use regular expressions for this because you can iterate over the letters AND check for duplicates at the same time. Also note:

  • by convention in java, methods start with lower case.
  • it would be best to take input elsewhere and pass to the method for evaluation.
  • A set is used to detect duplicates. If the addition returns false, it was already entered.
  • Check for length first. No need to do further testing if that fails.
  • Character.isLetter() to check for letters.
static int SIZE = 6;  // for testing.  Change it as you see fit.
String[] keys = {"Abcd","abcdea", "rstuvw", "xabers",
                 "#Sasrt", "abd3fr","abcde", "AaBbCc"};
for (String k : keys) {
    System.out.printf("%8s -> %b%n", k,encryptionKey(k));
}

prints

    Abcd -> false
  abcdea -> false
  rstuvw -> true
  xabers -> true
  #Sasrt -> false
  abd3fr -> false
   abcde -> false
  AaBbCc -> false
  ABCDEF -> true
  ABCdef -> true

The modified method.

    
public static boolean encryptionKey(String key) {
    
    Set<Character> seen = new HashSet<>();
    if (key.length() != SIZE) {
        return false;
    }
    for (char c : key.toCharArray()) {
        c = Character.toLowerCase(c);
        if (!(seen.add(c) && Character.isLetter(c))) {
            return false;
        }
    }
    return true;
}
WJS
  • 36,363
  • 4
  • 24
  • 39
  • Ok, I modified the code to ensure that upper and lower case of the same letter are considered duplicates. – WJS May 23 '21 at 22:15
0

According to your requirements, for a key to be valid, it must contain each letter of the [English] alphabet precisely once, since upper case letters and lower case letters are considered to be the same. In other words, if a key contains both a and A then it is invalid.

public static boolean encryptionKey(String key) {
    boolean valid = key != null  &&  key.length() == 26  &&  key.matches("^[a-zA-Z]+$");
    if (valid) {
        String str = key.toLowerCase();
        boolean[] alphabet = new boolean[26];
        char[] letters = str.toCharArray();
        for (char letter : letters) {
            int index = letter - 'a';
            if (index >= 0  &&  index < 26) {
                if (alphabet[index]) {
                    // repeated letter
                    valid = false;
                    break;
                }
                else {
                    alphabet[index] = true;
                }
            }
        }
    }
    return valid;
}

Firstly, the method checks that the parameter is not null and contains exactly 26 characters and that each character is a letter of the [English] alphabet.

Then all the letters in the parameter are converted to lower case since a valid key is not case sensitive.

A char is actually a number, so subtracting a from a gives 0 (zero). Subtracting a from b gives 1 (one) and so on.

A boolean array is implicitly initialized such that each element contains false.

The code iterates through all the letters in the key. If key contains the letter a (for example) then the first element in array alphabet is set to true. If the first array element is already true, that means key contains a more than one time which is invalid.

Abra
  • 19,142
  • 7
  • 29
  • 41