Search code examples
javamethodsrot13

Can't figure out what is wrong with my rot-13 method


I've been changing it around a lot. And, it just keeps getting worse. I can't figure out what I am doing wrong. From A-M, add 13. From M-Z, subtract 13. Before, at least I was receiving back letters. Now, they symbols.

import javax.swing.JOptionPane;

public class ExerciseE {

    public static String rot13(String s) {
        char value = 0;
        char position = s.charAt(0);
        String rev = "";

        for (int i = 0; i < s.length(); i++) {
            position = s.charAt(i); 
            if (position >= 65 && position <= 77) {
                value = (char) (position + 13);
            }
            if (position >= 78 && position <= 90) {
                value = (char) (position - 13);

            } else {
            }
            rev = (rev + value);

        }
        return rev;
    }

    public static void main(String[] args) {
        String s = JOptionPane.showInputDialog("Enter a phrase or sentence:");
        s = s.toUpperCase();
        System.out.println(rot13(s));     
    }

}

Solution

  • You're adding/subtracting from value not position...

    value = (char) (value + 13);
    

    Should probably be

    value = (char) (position + 13);
    

    And the same goes for the subtraction