2015-10-17 23 views
-2

對於實例我有一個錯誤,如果想要打印輸出for循環結束後cipher字符串:字符追加在字符串在運行時錯誤變量可能尚未初始化

System.out.print("Cipher Text IS : >>> "); 
for (int i = 0; i < len; i++) 
{ 
    char a = plainText.charAt(i); 
    for (int j = 0; j < allChar.length(); j++) 
    { 
     if (allChar.charAt(j) == a) 
     { 
      char c = allChar.charAt(j + key); 
      String cipher = "null" + c; 

      System.out.print("\t" + c); 
     } 
     System.out.println(cipher); 
    } 
} 
+0

你能發佈完整的錯誤信息嗎? – Gowtham

+0

先生我得到了點我沒有初始化密碼字符串之前for循環我定義的字符串在for循環邊界這就是爲什麼當我想訪問它的邊界然後它給出了一個錯誤謝謝你的評論.. –

+0

問題解決後,請保持原樣。只要接受幫助你解決問題的答案即可。 – Tom

回答

0

您需要更改這個(見我的評論在線):

for(int j=0; j<allChar.length(); j++) 
{ 
    if(allChar.charAt(j) == a)     
    { 
     char c= allChar.charAt(j+key); 
     String cipher = "null"+c; 

     System.out.print("\t"+c); 
    } 
    System.out.println(cipher); 
    // cipher is not defined/initialzed here. 
    // this is not the "end" of the loop but within its body, 
    // thus prints on every iteration 
} 

到:

cipher = ""; // initalize cipher 
for(int j = 0; j < allChar.length(); j++) 
{ 
    if(allChar.charAt(j) == a)     
    { 
     char c= allChar.charAt(j + key); 
     cipher += "null"+c; // don't know the logic here! 

     System.out.print("\t" + c); 
    } 
} 
System.out.println(cipher); // print result after loop 
+0

好的答案Sir Axel我很清楚你的觀點,但有一個小問題,你可以幫助我嗎?我發佈一個答案是ATBASH密碼的代碼,但它給出了一個錯誤,請你好好檢查一下... –

+0

主席先生,你有問題嗎? –

0

銀行經營ing代碼ATBASH密碼感謝幫助Dears

import java.util.Scanner; 

    class Asif 
    { 
     public static void main(String args[]) 
     { 
     String allchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
     Scanner a= new Scanner(System.in); 
     System.out.println("Enter the plainText For Cipher here "); 
     String plainText=a.nextLine(); 
     plainText=plainText.replaceAll(" ", ""); 
     plainText=plainText.toUpperCase(); 
     int len= plainText.length(); 
     int len1 = allchar.length(); 
     String cipher=""; 

     for(int i=0; i<len; i++) 
     { 
      char b=plainText.charAt(i); 
      for(int j=0; j<26; j++) 
      { 
       char c=allchar.charAt(j); 
       if(c == b) 
       { 
        int index=allchar.indexOf(c); 
      int position=25-index; 
        cipher+= allchar.charAt(position); 
        break; 

       } 
      } 
     } 
     System.out.println(cipher);  
    } 
} 
+0

您應該將新問題作爲新問題發佈。而不是自我評論或自我回答,以便社區可以查看和參與! –

+0

@AxelAmthor我不認爲這應該是一個問題。這更可能是他現在使用的完整代碼。還有另一個「答案」是一個新問題,但現在被刪除。 – Tom

+0

**我有一個問題**很清楚,我想。 –