Levi
Levi

Reputation: 53

How to loop back from "z" to "a" in the alphabet in Java?

Let me start off by saying I'm just learning Java. I'm having an issue looping back from the letter "z" to "a".

System.out.println("You chose Decryption!");
br.nextLine();

System.out.println("Type a message:");
String msg = br.nextLine();

String decryptedMessage = "";

for (int i = 0; i < msg.length(); i++){
    int decryption = msg.charAt(i);

    //Trying to loop back from "a" to "z"
    decryption = ((char)decryption % 26);
    decryptedMessage = decryptedMessage + ((char) (decryption - 1));

}

System.out.println(decryptedMessage);

I used the modulo operation decryption = ((char)decryption % 26); but instead of the letter "a", the code is giving me a bracket ([). Why isn't this working?

Upvotes: 0

Views: 1557

Answers (2)

Giovanni
Giovanni

Reputation: 4015

It's not clear what is the real problem. The code looks like a Caesar cipher problem, but you are asking for looping back form z to a. if you remove the line

decryption = ((char)decryption % 26); 

You'll get closer to decripting the message, because I think is that you choose a shift=1 to encrypt your messages. I'm guessing you are asking for looping form z to a because of the caesar cipher definition in wikipedia

If my guess is correct the problem is that the number representation of char is not 'a'=0, 'b'=1 and so on, but 'A' has a numeric representation of 65 and 'a' of 97. You are shifting a wrong number.

Upvotes: 3

Bonum Ursus
Bonum Ursus

Reputation: 46

Acccroding to ASCII table char 'a' is equale to 97 (DEC) as mentioned above. I highly recommend you look through this table. It will help you to understand what's going on under hood. So then your write 'a'+1 in fact it is conver to 97 + 1.

Upvotes: 3

Related Questions