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