문서 색인

2. 코드

package Test;

public class Caesar {
    public static void main(String[] args) {
        String str = "a B z";
        int offset = 4;
        Caesar caesar = new Caesar();
        System.out.println(caesar.get(str, offset));

    }

    private String get(String s, int offset) {
        StringBuffer sb = new StringBuffer();
        for ( int inx=0; inx<s.length(); inx++ ) {
            char c = s.charAt(inx);
            if ( c == ' ' ) {
                sb.append(c);
            } else {
                int ascii = (int)c;
                if ( ascii >= 65 && ascii <= 90 ) {
                    ascii += offset;
                    if ( ascii > 90 ) {
                        ascii -= (90-65)+1;
                    }
                    sb.append((char)ascii);
                } else if ( ascii >= 97 && ascii <= 122 ) {
                    ascii += offset;
                    if ( ascii > 122 ) {
                        ascii -= (122-97)+1;
                    }
                    sb.append((char)ascii);
                }
            }
        }
        return sb.toString();
    }
}