简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM