Java输入一行电报文字,将字母变成其下一字母(如’a’变成’b’……’z’变成’a’其它字符不变)。

要详细的代码
2025-02-24 17:22:33
推荐回答(2个)
回答1:

import java.util.*;
public class Yugi{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while(true){
            System.out.println("输入一行字母: ");
            String line = scan.nextLine();
            if(!line.matches("^[a-zA-Z]+$")){
                System.out.print("输入错误, ");
                continue;
            }
            String result = "";
            for(int i = 0; i < line.length(); i++){
                result += (char)((int)(line.charAt(i)) + 1);
            }
            System.out.println(result);
        }
    }
}

回答2:

public class Test {

public static void main(String[] args) {
String str = "hello world!";
String mima = encode(str);
System.out.println(mima);
}

public static String encode(String text){
String result;
char[] chars = text.toCharArray();
char[] chRes = new char[chars.length];
for(int i = 0; i < chars.length; i++){
if((chars[i] >= 'A' && chars[i] < 'Z') || (chars[i] >= 'a' && chars[i] < 'z')){
chRes[i] = (char) (chars[i] + 1);
}else if(chars[i] == 'z'){
chRes[i] = 'a';
}else if(chars[i] == 'Z'){
chRes[i] = 'A';
}else{
chRes[i] = chars[i];
}
}
result = String.valueOf(chRes);
return result;
}

}