字符串索引超出范围?

时间:2013-10-03 19:45:53

标签: java

我一直在用我的代码获取此错误“线程主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)); 

   }     
} 

2 个答案:

答案 0 :(得分:5)

字符串索引从0运行到length - 1,因此您正在运行字符串compress的末尾。从

更改for循环条件
for (count = 0; count <= compress.length(); count++) 

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

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

答案 1 :(得分:1)

指数范围为0 to length-1。尝试使用: -

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

而不是

for (count = 0; count <= compress.length(); count++)  
相关问题