【问题标题】:String index out of range?字符串索引超出范围?
【发布时间】:2013-10-03 19:45:53
【问题描述】:

我的代码不断出现此错误:

“线程主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));
    }     
} 

【问题讨论】:

    标签: java


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      索引范围为0 to length-1。尝试使用:-

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

      而不是

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-13
        • 2016-02-19
        • 2012-03-02
        • 2016-02-10
        • 2021-01-30
        • 2019-12-24
        • 1970-01-01
        相关资源
        最近更新 更多