2015-02-10 184 views
0

我可以知道我應該怎麼做,如果我想加密40個字符,但我只能加密與我做的代碼的第一個字符。加密字符串

System.out.println("Enter character: "); 
    sentence = scan.nextLine(); 
    String random; 
    System.out.println("Enter random character: "); 
    random = scan.nextLine(); 


    conv = random.charAt(sentence.indexOf(sentence)); 
    back = sentence.charAt(random.indexOf(conv)); 

    System.out.println("U want to encrypt or decrypt?"); 
    answer = scan.nextLine(); 



    if(answer.equals("encrypt")) 
    { 
    System.out.println("The original character is:" +sentence); 
    System.out.println("The encrypted character is:" +conv); 
    } 
    else 
    { 
    System.out.println("The decrypted character is:" +back); 

    } 
    // TODO code application logic here 
    } 

}

回答

0

很明顯,當你excuting語句只有一次只有一個字符將得到加密。您需要使用循環遍歷輸入字符串中的所有字符。我給大家舉一個例子:

String conv = ""; 
for (int i = 0; i < senentence.length(); i++) { 
    conv.append(...); 
} 

你追加什麼,取決於你所使用的算法和輸入的字符串有多長。使用random.charAt(i)只會使用隨機字符串,並最終拋出異常。