2015-02-11 48 views
0

我寫了凱撒密碼的代碼,但它不工作...請幫我解決這個問題。我需要幫助理解java.lang.StringIndexOutOfBoundsException

import java.io.IOException; 
import java.util.Scanner; 

public class test1 { 

    public static void main(String[] args) throws IOException { 
     System.out.println("enter the String"); 
     StringBuffer str = new StringBuffer(new Scanner(System.in).nextLine()); 
     System.out.println("encrypting the String . . ." +str); 

     for(int j=0; j<str.length(); j++){ 
      for(int i=0; i<256; i++) { 
       if((char)i == str.charAt(j)){ 
        str.setCharAt(j, (char)(i+3)); 
       } 
      } 
     } 
     System.out.println("encrypted String . . ."); 
    } 
} 

這裏您的解決方案的作品並沒有更多的java.lang.StringIndexOutOfBoundsException 現在還有另一個問題發生。 。 。 。 我嘗試了不同的輸入,但它一直回覆相同的答案:??????

+3

'J開頭<= str.length()'索引是基於0。 – 2015-02-11 06:32:48

+0

你的建議解決了我的問題。 。 。但是現在當我運行程序時出現另一個錯誤,它顯示答案?????我嘗試了不同的輸入,但每次只有一個輸出:?????? – 2015-02-11 08:05:39

回答

1

使用

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

1

java中的字符串是基於零的。所以,你必須刪除=在你的第一個循環:

for(int j=0; j<str.length(); j++){ 
1

for(int j=0; j<str.length(); j++) // string index length are 0 based

,而不是字符串的字符總是以指數0開始,這意味着如果你存儲

String str="text"; 

隨後

str.charAt(0) // return "t" 
str.charAt(1) // return "e" 
str.charAt(2) // return "x" 
str.charAt(3) // return "t" 

,如果你叫str.charAt(4)

它會拋出java.lang.StringIndexOutOfBoundsException這意味着,在 指數,你的目標,以獲取數據從超出邊界。

所以,只要改變你的循環,因爲每個人都建議。 像這樣,

 for(int j=0; j<str.length(); j++){ 
      for(int i=0; i<256; i++) { 
       if((char)i == str.charAt(j)){ 
        str.setCharAt(j, (char)(i+3)); 
       } 
      } 
     } 
0

j<= str.length() to j< str.length()使用在for(int j=0; j<str.length(); j++)作爲索引從0