String compression giving error index out of bound

package com.assignment;

import java.util.Scanner;

public class demodemo {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner sc = new Scanner(System.in);

// String d =“ss”;
// System.out.println(d.length());
String s = sc.next();
StringBuilder ans = new StringBuilder();
for(int i=0;i<s.length();i++)
{

	char temp = s.charAt(i);
	int count =1;
	
	if(i<=s.length()-1) {
	while(temp==s.charAt(i+1))
	{
		count++;
		i++;
		
	}
	}
	else
	{
		temp = s.charAt(i);
		count =1;
	}
	ans.append(temp);
	ans.append(count);
	
	
}
	
System.out.println(ans.toString());

}

}