user2844184
user2844184

Reputation: 1

String index out of range?

I keep getting this error with my code:

"exception in thread main java.lang.stringindexoutofboundsexception string index out of range"

What is the problem?

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

Upvotes: 0

Views: 1880

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

The Index range from 0 to length-1. Try to use:-

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

instead of

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

Upvotes: 1

rgettman
rgettman

Reputation: 178243

The string indexes run from 0 to length - 1, so you are running off the end of the string compress. Change your for loop condition from

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

to

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

This way, when count reaches compress.length(), then the for loop is stopped before that index is used.

Upvotes: 5

Related Questions