public String getPass(String str){
String str="";
for(int i=0;ichar ch=str.charAt(i); //得到单个字符ch;
if(ch>64 && ch<91){ //成立=>ch是大写字母
str+=(char)(155-ch); //大写对应字母之和:155 eg:'A'+'Z'=155
}else if(ch>96 && ch<123){ //成立则ch是小写字母
str+=(char)(219-ch); //小写对应字母之和:219 如:'a'+'z'=219
}else {
str=""; //若进入此处,则说明str中有非字母字符
return str; //直接退出
}
}
return str; //返回str的值;
}
楼主估计是新手,此处程序鄙人就不进一步优化。(可优化)
import java.util.HashMap;
import java.util.Map;
public class EncryptDemo {
/** 01234567890122109876543210*/
private static String DEFAULT = "abcdefghijklmnopqrstuvwxyz";
private static String regex = "[a-zA-Z]";
private static MapupperMap = new HashMap ();
private static MaplowerMap = new HashMap ();
static {
int length = DEFAULT.length();
for(int i=0;ichar key = DEFAULT.charAt(i);
char value = DEFAULT.charAt(length-1-i);
lowerMap.put(key, value);
}
String DEFAULT1 = DEFAULT.toUpperCase();
for(int i=0;ichar key = DEFAULT1.charAt(i);
char value = DEFAULT1.charAt(length-1-i);
upperMap.put(key, value);
}
}
public static String encryptString(String string) throws Exception {
StringBuilder sb = new StringBuilder();
for(char ch : string.toCharArray()) {
if(check(ch)) {
sb.append((upperMap.containsKey(ch)?upperMap.get(ch):lowerMap.get(ch)));
}else{
throw new Exception("含有非法字符");
}
}
return sb.toString();
}
public static boolean check(char ch) {
String str = new Character(ch).toString();
if(str.matches(regex)){
return true;
}else {
return false;
}
}
private EncryptDemo(){}
public static void main(String[] args) throws Exception {
System.out.println(EncryptDemo.encryptString("HelloWorld"));
}
}
你看看合不合要求,仅供参考
public class ChangeChar {
/**
* @param args
*/
public static void main(String[] args) {
String input = null;
Scanner scanner = new Scanner(System.in);
input = scanner.next();
StringBuffer changed = new StringBuffer();
for(int i = 0;i < input.length();i++){
char x = input.charAt(i);
if(input.charAt(i) >= 'a' && input.charAt(i) <= 'z'){
x = (char) ('a' + 'z' - x);
changed.append(x);
}else if(x >= 'A' && x <= 'Z'){
x = (char) ('A' + 'Z' - x);
changed.append(x);
}else{
continue;
}
}
System.out.println(changed);
}
}
加减法的问题 这个还不简单么 注意ASCII字符集值即可 只有26个字母 对应输出即可