题解 | #字符串加解密#

字符串加解密

http://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while(in.hasNextLine()){
            String codeBefore=in.nextLine();
            String codeAfter=in.nextLine();
            //加密
            for(int i=0;i<codeBefore.length();i++){
                if(isAlpha(codeBefore.charAt(i))){//字母的处理
                    if(codeBefore.charAt(i)=='Z'){
                        System.out.print('a');
                    }else if(codeBefore.charAt(i)=='z'){
                        System.out.print('A');
                    }else{
                        System.out.print(transform((char)(codeBefore.charAt(i)+1)));
                    }
                }else{//数字的处理
                    if(codeBefore.charAt(i)=='9'){
                        System.out.print('0');
                    }else{
                        System.out.print((char)(codeBefore.charAt(i)+1));
                    }
                }
            }
            System.out.println();//换行
            //解密
            for(int i=0;i<codeAfter.length();i++){
                if(isAlpha(codeAfter.charAt(i))){//字母的处理
                    if(codeAfter.charAt(i)=='A'){
                        System.out.print('z');
                    }else if(codeAfter.charAt(i)=='a'){
                        System.out.print('Z');
                    }else{
                        System.out.print(transform((char)(codeAfter.charAt(i)-1)));
                    }
                }else{//数字的处理
                    if(codeAfter.charAt(i)=='0'){
                        System.out.print('9');
                    }else{
                        System.out.print((char)(codeAfter.charAt(i)-1));
                    }
                }
            }
            System.out.println();//换行
        }

    }
    //大小写字母转换
    public static char transform(char ch){
        if(ch>='A' && ch<='Z'){
            return (char)(ch+32);
        }
        return (char)(ch-32);
    }
    //判断是否是字母
    public static boolean isAlpha(char ch){
        if(ch>='0' && ch<='9'){
            return false;
        }
        return true;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务