老师布置的作业,哈,保存到网上。
package net.as.cn;
/**
* 2013.3.22 am 替换算法
*
* @author chenas
*
*/
public class MyTiHuan {
public final int smalla = 97;
public final int bigA = 65;
public final int smallz = 122;
public final int bigZ = 90;
public final int space = 32;
public final int smallZero = 96;
public final int bigZero = 64;
/**
* 判断是否为小写字母
*
* @param a
* @return
*/
public boolean isSmall(char a) {
if (a >= 97 && a <= 122) {
return true;
} else
return false;
}
/**
* 判断是否为大写字母
*
* @param A
* @return
*/
public boolean isBig(char A) {
if (A >= 65 && A <= 90) {
return true;
} else
return false;
}
/**
* 判断是否为空格
*
* @param spa
* @return
*/
public boolean isSpace(char spa) {
if (spa == space) {
return true;
} else
return false;
}
/**
* 检查非法字符
*
* @param a
* @return
*/
public boolean isPass(char a) {
if (a == space) {
return true;
} else if (a >= smalla && a <= smallz) {
return true;
} else if (a >= bigA && a <= bigZ) {
return true;
}
return false;
}
/**
*
* 加密
*
* @param mingwen
* 明文
* @param yiwei
* 右移的位数
* @return 密文
*
*/
public String enCode(String mingwen, int yiwei) {
StringBuffer sBuff = new StringBuffer();
char[] mw = mingwen.toCharArray();
for (int i = 0; i < mw.length; i++) {
char temp = 'a';
char c = mw[i];
if (isPass(c)) {
if (isSmall(c)) {
temp = (char) (c + yiwei);
if (!isPass(temp)) {
temp = (char) (temp - smallz + smallZero);
}
} else if (isBig(c)) {
temp = (char) (c + yiwei);
if (!isPass(temp)) {
temp = (char) (temp - bigZ + bigZero);
}
} else if (isSpace(c)) {
temp = c;
}
} else {
return sBuff.append("输入中带有非法字符!").toString();
}
sBuff.append(temp);
}
return sBuff.toString();
}
/**
* 解密
*
* @param miwen
* 密文
* @param yiwei
* 左移的位数
* @return 明文
*/
public String deCode(String miwen, int yiwei) {
StringBuffer sBuff = new StringBuffer();
char[] mw = miwen.toCharArray();
for (int i = 0; i < mw.length; i++) {
char temp = 'a';
char c = mw[i];
if (isPass(c)) {
if (isSmall(c)) {
temp = (char) (c - yiwei);
if (!isPass(temp)) {
temp = (char) (smallz - smallZero + temp);
}
} else if (isBig(c)) {
temp = (char) (c - yiwei);
if (!isPass(temp)) {
temp = (char) (bigZ - bigZero + temp);
}
} else if (isSpace(c)) {
temp = c;
}
} else {
return sBuff.append("密文中带有非法字符!").toString();
}
sBuff.append(temp);
}
return sBuff.toString();
}
public static void main(String[] args) {
MyTiHuan mt = new MyTiHuan();
String miw = mt.enCode("My name is Jack", 3);
System.out.println(miw);
String mingw = mt.deCode(miw, 3);
System.out.println(mingw);
}
}