Battleroid
Battleroid

Reputation: 881

Unknown question marks appearing when printing characters

For a class project I'm producing a ROT13-like encryption method, the only difference in ours is that instead of the 13th character away, it is the 9th. Surprisingly I was able to produce something that works on lowercase letters to see if my method works.

It works, but for some reason, odd characters appear, more commonly question marks and sometimes just extra characters that aren't in the original character array.

For example: my name results in ljb|nh?. | and ? shouldn't be there, at least to my knowledge they shouldn't.

Can anyone tell me why this might be happening by looking at my code?

public class Encrypt {
    public static void main(String[] args) {
        // Lower a-z: 97-122; Higher A-Z: 65-90
        jumble("casey");
    }
    public static void jumble(String input) {
        char[] phraseChar = input.toCharArray();
        // StringBuilder output = new StringBuilder("");

        for (int i = 0; i < phraseChar.length; i++) {
            System.out.print("" + phraseChar[i]);
        }

        System.out.println();

        for (int j = 0; j < phraseChar.length; j++) {
                int i = (int) phraseChar[j];
                if (i >= 'a' && i <= 'z') {
                    i += 9;
                    if (i > 'z') {
                        int newChar = 96 + (i - 'z');
                        System.out.print((char) newChar);
                    }
                    System.out.print((char) i);
            }
        }
    }
}

Anyone who can help me pinpoint this problem is a saint.

Upvotes: 0

Views: 2735

Answers (1)

SJuan76
SJuan76

Reputation: 24875

if (i >= 'a' && i <= 'z') { 
   i += 9; 
   if (i > 'z') { 
       int newChar = 96 + (i - 'z'); 
       System.out.print((char) newChar); 
   } 
   System.out.print((char) i);
 }

If i is out of bounds, you are printing both the "corrected" character and the original out-of-bounds one. Put an else

I am not a saint. Use a debugger for these things. That knowledge will be handy in the future.

Upvotes: 2

Related Questions