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));
    }     
} 
4

2 回答 2

5

字符串索引从0to运行length - 1,因此您正在运行字符串的末尾compress。改变你的for循环条件

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

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

这样,当count到达时compress.length()for循环在使用该索引之前停止。

于 2013-10-03T19:46:47.627 回答
1

指数范围从0 to length-1. 尝试使用:-

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

代替

for (count = 0; count <= compress.length(); count++)  
于 2013-10-03T19:47:07.787 回答