2014-03-30 62 views
-2

我是新來的Java,並具有使用字符串和麻煩字符的分配,當他們 交織在一起。這裏凱撒程序不會運行,因爲必須比較 字符和字符串之間的分配。請幫助 謝謝。的Java加密凱撒代碼

class Caesar { 
    public static char encrypt(String str) { 
     String result = ""; 
     String x; 
     for (String ch : str) { 
      x = plainalphabet.indexOf(ch); 
      if (x != -1) { 
       result = result + cipheralphabet.charAt(x); 
      } 
      else { 
       result = result + ch; 
      } 
     } 
     return result; 
    } 

    public static void main(String args[]) { 
     String plainalphabet = "abcdefghijklmnopqrstuvwxyz"; 
     String cipheralphabet = "defghijklmnopqrstuvwxyzabc"; 
     System.out.println(encrypt("James")); 
    } 
} 
+1

請分享你得到的錯誤,以及你得到它的線。 – Mureinik

+2

cipheralphabet沒有在'encrypt'範圍內定義。您可能想要了解變量作用域 –

+2

'for(String ch:str)'是一個增強型for語句。無論你使用什麼,都必須實現'Iterable'。無論如何,使用標準的'for'循環會更好(因爲語法錯誤,並且您想在迭代中使用索引)。 – Makoto

回答

1

可能的解決辦法:

public class Caesar { 
    private static final String PLAIN = "abcdefghijklmnopqrstuvwxyz"; // fix scope 

    private static final String CIPHER = "defghijklmnopqrstuvwxyzabc"; // fix scope 

    public static String encrypt(String str) 
    { 
     String result = ""; 
     int x; // indexOf returns int 
     for (final char ch : str.toCharArray()) { // str is not an Iterable 
      x = PLAIN.indexOf(ch); 
      if (x != -1) { 
       result = result + CIPHER.charAt(x); 
      } else { 
       result = result + ch; 
      } 
     } 
     return result; 
    } 

    public static void main(String args[]) 
    { 
     System.out.println(encrypt("James")); 
    } 
} 

(社區wiki,因爲它幾乎沒有答案,幾乎沒有問題)

+0

變化爲:對於(燒焦CH:str.toLowerCase()toCharArray())<--- J用詹姆斯犯規平移。 –

+0

對於一個小的加速,不是'x = PLAIN.indexOf(ch)',而只是減去'x = ch - 'a'';假設ASCII(並且你轉換爲小寫)...... – user949300

+0

傢伙,只需編輯並修改/改變它;)真正的算法將會是string => char => shift => string –

0

所有的簽名首先應改爲

public static String encrypt(String str) 

而不是爲(字符串CH:STR)使用

for (int i = 0; i < str.length(); i++) 
+5

不,不,不。不是'i <= str.length()';它是'我 Makoto

+0

@Makoto不確定))) – xuesheng