普通写法, 遍历每个字符进行加密
public static void main1 (String[] args) {
Scanner sc = new Scanner(System.in);
String strs = sc.nextLine();
char[] chss = strs.toCharArray();
for(int i = 0;i < chss.length; i++){
if(chss[i] <= 'z' && chss[i] >= 'a'){
chss[i]+=3;
if(chss[i] > 'z'){
chss[i]-=26;
}
}else if(chss[i] <= 'Z' && chss[i] >= 'A'){
chss[i]+=3;
if(chss[i] > 'Z'){
chss[i]-=26;
}
}
}
for(char c : chss){
System.out.print(c);
}
}
stream流写法,用map对每个字符进行加密处理
//写法2
public static void main2 (String[] args) {
Scanner sc = new Scanner(System.in);
String strs = sc.nextLine();
//Arrays.stream() 只接收 对象数组或int long double数组
//chars() 将String转换为 整数流
//mapToObj 将整数流映射 回 字符流
strs.chars().map(c -> {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
c += 3;
if ((c > 'z' && c <= 'z' + 3) || (c > 'Z' && c <= 'Z' + 3)) {
c -= 26;
}
}
return c;
}).mapToObj(c -> (char) c).forEach(System.out::print);
}
在写法2的基础上
public class kaisaCode {
//写法3 方法引用
public static void main3 (String[] args) {
Scanner sc = new Scanner(System.in);
String strs = sc.nextLine();
//静态方法引用
strs.chars().map(kaisaCode::jiami).mapToObj(c -> (char) c).forEach(System.out::print);
}
//静态方法
public static int jiami(int c){
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
c += 3;
if ((c > 'z' && c <= 'z' + 3) || (c > 'Z' && c <= 'Z' + 3)) {
c -= 26;
}
}
return c;
}
}