public class KingPassword
{
public static void main(String[] args)
{
String inputString;//用户输入
int choice;
choice = Integer.valueOf(JOptionPane.showInputDialog( "对字符串加密输入1,对字符串解密输入2" ));
//把用户输入的字符串1或2转换为整型1或2
if(choice == 1)
{
inputString = JOptionPane.showInputDialog( "请输入要加密的字符串:" );
char a[] = inputString.toCharArray();
int length = inputString.length();//求出字符数组的长度
for(int i = 0;i < length;i++)
{
if(a[i] == 'x')
a[i] = 'a';
else if(a[i] == 'y')
a[i] = 'b';
else if(a[i] == 'z')
a[i] = 'c';
else if(a[i] == 'X')
a[i] = 'A';
else if(a[i] == 'Y')
a[i] = 'B';
else if(a[i] == 'Z')
a[i] = 'C';
else
a[i] += 3;
}//对字符串中的每个字符依次加密
String outputString = new String(a);//把字符数组再转回字符串
JOptionPane.showMessageDialog( null, outputString,
"加密后的字符串为",
JOptionPane.INFORMATION_MESSAGE );
//使用对话框来显示加密后的字符串
}
else if(choice == 2)
{
inputString = JOptionPane.showInputDialog( "请输入要解密的字符串:" );
char a[] = inputString.toCharArray();//把字符串转化为字符数组
int length = a.length;//求出字符数组的长度
for(int i = 0;i < length;i++)
{
if(a[i] == 'a')
a[i] = 'x';
else if(a[i] == 'b')
a[i] = 'y';
else if(a[i] == 'c')
a[i] = 'z';
else if(a[i] == 'A')
a[i] = 'X';
else if(a[i] == 'B')
a[i] = 'Y';
else if(a[i] == 'C')
a[i] = 'Z';
else
a[i] -= 3;//每个字符后移三位
}//对字符串中的每个字符依次加密
String outputString = new String(a);
JOptionPane.showMessageDialog( null, outputString,
"解密后的字符串为",
JOptionPane.INFORMATION_MESSAGE );
//使用对话框来显示加密后的字符串
}
else
{
JOptionPane.showMessageDialog( null, "输入有误",
"错误提示!",
JOptionPane.INFORMATION_MESSAGE );
}//对非法输入有错误提示
}
}
(二)动手动脑之String.equals()方法
public class StringEquals {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String s1=new String("Hello");
String s2=new String("Hello");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
String s3="Hello";
String s4="Hello";
System.out.println(s3==s4);
System.out.println(s3.equals(s4));
}
}
Java中的equals()方法是在Object类中定义,equals 方法被用来检测两个对象是否相等,即两个对象的内容是否相等。在实际使用的过程中,由于=是检测两个对象的地址,所以我们就可以重写equals()方法比较内容是否相同。
(三)整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明。
length()//求字符串长度
使用说明:
String s=”jdbfkjdbfksdjbfksjd”;
System.out.println(s.length());
charAt(index)//index 是字符下标,返回字符串中指定位置的字符
使用说明:
String s=“love”;
System.out.println(s.charAt(3));
getChars()//将字符从此字符串复制到目标字符数组
使用说明:
String str = "hbjhshvjh";
Char[] ch = new char[8];
str.getChars(2,5,ch,0);
replace()//替换字符串
使用说明:
String s=”abc”;
System.out.println(s.replace(“abc”,”xyz”));
toUpperase()//将字符串全部转换成大写
使用说明:
System.out.println(new String(“hi”).toUpperCase());
toLowerCse()//将字符串全部转换成小写
使用说明:
System.out.println(new String(“HI”).toLowerCase());
trim()//是去两边空格的方法
使用说明:
String x=”ab c”;
System.out.println(x.trim());
toCharArray(): // 将字符串对象中的字符转换为一个字符数组
使用说明:
String x=”abcd”;
char myChar[]=x.toCharArray();
System.out.println(“myChar[1]:”+myChar[1]);