2013-10-03 59 views
0

我一直得到這個錯誤與我的代碼「線程主要java.lang.stringindexoutofboundsexception字符串索引超出範圍異常」我無法弄清楚是什麼問題?字符串索引超出範圍?

import java.util.Scanner; 
public class Compress { 

public static void main(String[] args) 
{ 
    Scanner scan = new Scanner(System.in); 
    System.out.println("Enter a string: "); 
    String compress = scan.nextLine(); 
    int count = 0; 

    for (count = 0; count <= compress.length(); count++) 
    { 
     while(count +1 < compress.length() && compress.charAt(count) == compress.charAt(count  + 1)) 
    { 
      count = count + 1; 
     } 
     System.out.print(count + "" + compress.charAt(count)); 

    }  
} 
+1

的Java =的Javascript。 –

回答

5

字符串指標運行從0length - 1,所以你正在運行斷絃compress結束。從

for (count = 0; count <= compress.length(); count++) 

更改for循環條件

for (count = 0; count < compress.length(); count++) 

這樣,當count達到compress.length(),則使用該索引之前for循環停止。

1

指數範圍從0 to length-1。嘗試使用: - 的

for (count = 0; count < compress.length(); count++) 

代替

for (count = 0; count <= compress.length(); count++) 
相關問題