問題:提示用戶輸入一個英文字符串或者要解密的字符串,然后通過掃描儀獲取用戶輸入的字符串,經過加密或者解密后,把字符串輸出。
import java.util.Scanner;public class Encryption {public static void main(String[] args) {Scanner scan = new Scanner(System.in);System.out.println("請輸入一個英文字符串或解密字符串");String password = scan.nextLine();//獲取用戶輸入,這里可以有空格;char [] array = password.toCharArray();//獲取字符數組for(int i = 0;i<array.length;i++){//遍歷字符數組array[i] = (char) (array[i]^20000);//對每個數組元素進行異或運算}System.out.println("加密或解密結果如下:");System.out.println(new String (array));//輸出密鑰}}
這里的代碼第七行scan.nextLine();可以得到帶空格的字符串。
import java.util.Scanner;public class Encryption {public static void main(String[] args) {Scanner scan = new Scanner(System.in);System.out.println("請輸入一個英文字符串或解密字符串");String password = scan.next();//獲取用戶輸入,這里不能有空格;char [] array = password.toCharArray();//獲取字符數組for(int i = 0;i<array.length;i++){//遍歷字符數組array[i] = (char) (array[i]^20000);//對每個數組元素進行異或運算}System.out.println("加密或解密結果如下:");System.out.println(new String (array));//輸出密鑰}}
這里的代碼第七行scan.next();不能得到帶空格的字符串。
代碼第八行的引用java String類中的這個方法:
char [] array = password.toCharArray();
toCharArray() 方法將字符串轉換為字符數組。
語法
public char[] toCharArray()
參數
無
返回值
字符數組。
實例
public class Test {public static void main(String args[]) {String Str = new String("www.runoob.com");System.out.print("返回值 :" );System.out.println( Str.toCharArray() );}
}
以上程序執行結果為:
返回值 :www.runoob.com
返回值是一個數組的形式。