標籤:== ann 問題 過程 數組元素 getch scanner bool while
第一題
字串加密問題
1.程式設計思想
讀入字串,然後擷取其長度,利用charAt()擷取每個位置字元並且對字元加3實現加密處理,並存入新字串中。如果遇到xyz則減26存入。
2.程式流程圖
3.程式原始碼
import java.util.Scanner;import java.util.Random;public class StringJiami {public static void main(String[] args) {// TODO Auto-generated method stubStr s=new Str();Scanner input=new Scanner(System.in);System.out.print("1 字串加密\n2 字串解密\n請選擇:");int choose=input.nextInt();if(choose==1){String str;System.out.print("請輸入要加密的字串:");input.nextLine();str=input.nextLine(); //輸入字串s.setStr(str);System.out.println("加密後為:"+s.jiami());}if(choose==2){System.out.print("請輸入要解密的字串:");input.nextLine();String str=input.nextLine(); //輸入字串s.setStr(str);System.out.println("解密後為:"+s.jiemi());}}}class Str{private String str;public void setStr(String a){this.str=a;}public String jiemi(){int l=str.length(); //計算字串長度String newstr=""; //設定Null 字元串儲存解密後內容char c;for(int i=0;i<l;i++){c=str.charAt(i); //提起第i個字元if((c>=‘a‘&&c<=‘c‘)||(c>=‘A‘&&c<=‘C‘))c=(char)(c+26); //解密處理if(c==‘ ‘)c=c;elsec=(char)(c-3);newstr+=c;}return newstr; //返回解密後字串}public String jiami(){int l=str.length(); //計算字串長度String newstr=""; //設定Null 字元串儲存解密後內容char c;for(int i=0;i<l;i++){c=str.charAt(i); //提起第i個字元if((c>=‘x‘&&c<=‘z‘)||(c>=‘X‘&&c<=‘Z‘))c=(char)(c-26); //解密處理if(c==‘ ‘)c=c;elsec=(char)(c+3);newstr+=c;}return newstr; //返回解密後字串}}
4驗證結果
第二題
總結String類的一些方法的使用說明
Equals的實現方法
String anotherString = (String)anObject;
字串是一個引用資料類型,本身是String個對象,
在這裡把傳進來的anObject這個對象,賦給anotherString (需要類型轉換)
他當然可以調用String類裡的成員,你說的count、value、offset都是String的成搜尋員
int n = count;//這個count是原始字串的長度
if (n == anotherString.count) { //把字串長度和要比較的字串長度對比,長度都不同的話就不用比字串內容了
char v1[] = value;//把原始字串義字元形式存入數組
char v2[] = anotherString.value; //把要比較字串義字元形式存入數組
int i = offset;//數組下標
int j = anotherString.offset; //????
while (n-- != 0) { //遍曆數組,比較 數組元素是否相同
if (v1[i++] != v2[j++])
return false;//在遍曆的過程中如果有不同的就返回false;
} //你如果用過equals這個方法應該知道它返回的是boolean值
return true;
}
}
return false;
}
(1)Length():是表示字串長度的一個屬性。可以用來統計字串的長度也可以設定返回數組元素的個數。
(2)charAt():方法返回指定索引處的char值。索引範圍是從0到length() - 1。對於數組索引,序列的第一個char值是在索引為0,索引1,依此類推.
(3)void getChars(int srcBegin, int srcEnd,char[] dst, int dstbegin):該方法將目標字元拷貝到字串中其中,srcBegin為拷貝的起始位置,srcEnd為拷貝的結束位置,字串數值dst為目標字元數組,dstBegin為目標字元數組的拷貝起始位置
(4)replace():String replace(char oldChar,char newChar);//將字串中第一個oldChar替換為newChar;
(5)toUpperCase()將字元轉換為大寫
(6)toLowerCase()將字元轉換為小寫
(7)Trim()刪除字串開始和結束部分的空格,然後返回刪除後的結果。不刪除字串中間的空格
(8)toCharArray()將String類型轉化為字元數組型
java課堂作業4