0
public static void main(String[] args) {
    String message, encryptedMessage = "";
    int key;
    char ch;
    Scanner sc = new Scanner(System.in);
    
    key = sc.nextInt();
    
    message = sc.nextLine();
    sc.useDelimiter(" ");
    
    // I think the problem is in the encrypting formula.

    for(int i = 0; i < message.length(); ++i){
        ch = message.charAt(i);
        
        if(ch >= 'a' && ch <= 'z'){
            ch = (char)(ch + key);
            
            if(ch > 'z'){
                ch = (char)(ch - 'z' + 'a' - 1);
            }
            
            encryptedMessage += ch;
        }
        else if(ch >= 'A' && ch <= 'Z'){
            ch = (char)(ch + key);
            
            if(ch > 'Z'){
                ch = (char)(ch - 'Z' + 'A' - 1);
            }
            
            encryptedMessage += ch;
        }
        else {
            encryptedMessage += ch;
        }
    }
    
    while(sc.hasNext()){
        System.out.println(sc.next()+encryptedMessage);
    }
    sc.close();
}

This is my code and I use delimiter for the text. The input I use doesn't get encrypted. I don't understand what the problem is. Can somebody help me with the code?

Abra
  • 11,631
  • 5
  • 25
  • 33

1 Answers1

0

Your problem is with the way you are accepting the [encryption] key and the message to encrypt. Using the code in your question, you need to enter an integer immediately followed by the message, for example.

1Abc xyz.

In the above example, the key is 1 (one) and the message is Abc xyz. You hit the <ENTER> key after entering the the last letter in the message and your code correctly generates the encrypted message which, according to my example above, is

Bcd yza.

If you hit <ENTER> after entering the [encryption] key (which is 1 in my example, above) then the "message" is an empty string. That's why it appears that your message is not encrypted.

If you step through your code with a debugger, then you would discover that "message" is an empty string. All good IDEs have a debugger. You should learn to use it.

Perhaps Scanner is skipping nextLine() after using next() or nextFoo()? will help you understand how Scanner class works.

By the way, you should not close a Scanner that wraps System.in. You can safely ignore any warnings your IDE may display about not closing the Scanner. Also, your last while loop is not required. Simply print encryptedMessage, i.e.

System.out.println(encryptedMessage);
Abra
  • 11,631
  • 5
  • 25
  • 33