2013-07-18 21 views
0

我想提出一個密碼,出於某種原因,我輸入後給了我這些錯誤的文字:在哪裏(什麼)是錯誤 - java的密碼

enter string to be encrypted: 
hello world 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 
    at chipher.cipher.encrypt(cipher.java:21) 
    at chipher.cipher.main(cipher.java:9) 

這是我的代碼:

package chipher; 
import java.util.Scanner; 
public class cipher { 
public static int x; 
public static int y; 
public static Scanner jon = new Scanner(System.in); 
    public static void main(String[] args) { 
     System.out.println("enter string to be encrypted: "); 
     encrypt(jon.nextLine()); 
     } 


public static void encrypt(String tocipher){ 
    double lngth = tocipher.length(); 
    tocipher.toLowerCase(); 
    char[] mynamechars = tocipher.toCharArray(); 
    char[] alphabet = new char[]{'a', 'b', 'c', 'd' , 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
for(int i = 0; i<lngth;) 
    for(int x = 0; x<26;){ 
     y = x + 1; 
if(mynamechars[i] == alphabet[x]){ 
    mynamechars[i] = alphabet[y]; 
} 
i++; 
x++; 
} 
    String text = String.valueOf(mynamechars); 
    System.out.println(text); 
} 
} 

我不知道發生了什麼,我只是學習java,所以它可能是一些基本的東西,所以只是在這裏忍受。

+0

和是的我知道這是一個非常基本的密碼,但只是試圖幫助,請 – user2224340

+0

你能更好地格式化你的代碼嗎? –

+0

'tocipher.toLowerCase();'沒有效果。 – SLaks

回答

0

你正在做

mynamechars[i] 

高達25個指標,它似乎您輸入的輸入只是長

0

你有兩個錯誤的10個字符。你的第一個是由於你的方法寫的for循環和你沒有縮進:

for (int i = 0; i < lngth;) { 
    for (int x = 0; x < 26;) { 
     y = x + 1; 

     if (mynamechars[i] == alphabet[x]) { 
      mynamechars[i] = alphabet[y]; 
     } 

     i++; 
     x++; 
    } 

    String text = String.valueOf(mynamechars); 
    System.out.println(text); 
} 

您在內環與x沿增加i。你應該增加它是循環之外:

for (int i = 0; i < lngth; i++) { 
    for (int x = 0; x < 26; x++) { 
     y = x + 1; 

     if (mynamechars[i] == alphabet[x]) { 
      mynamechars[i] = alphabet[y]; 
     } 
    } 

    String text = String.valueOf(mynamechars); 
    System.out.println(text); 
} 

再就是與y問題。

x範圍從025,所以y將範圍從126alphabet沒有索引爲26(即信件的27 th)的元素,這會導致您的錯誤。

你要麼必須檢查手動的話:

if (mynamechars[i] == alphabet[x]) { 
    if (y == 26) { 
     y = 0; 
    } 

    mynamechars[i] = alphabet[y]; 
} 

或者完全擺脫的y,使用模運算符來繞回到開頭:

if (mynamechars[i] == alphabet[x]) { 
    mynamechars[i] = alphabet[(x + 1) % alphabet.length]; 
} 
0

添加System.out.println以上y = x + 1;,你應該得到意外的例外:)