Click here to Skip to main content
15,850,753 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I was trying to solve a problem.
problem link: Problem - B - Codeforces[^]

I solved the problem logically. But Java index bound checking is occurring problems. I wrote a additional if statement to avoid any indexOutOfBound. Though I solved bound checking issue the same way(adding if statement) before, but this time it is not working.

Error Messages:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 3, end 2, length 10
	at java.base/java.lang.String.checkBoundsBeginEnd(
	at java.base/java.lang.String.substring(
	at pac1.Simple1.main(

What I have tried:

<pre>package pac1;
import java.util.Scanner;
import java.lang.String;
public class Simple1{
	public static void main(String[] args) {
		Scanner sc = new Scanner(;
		int t = sc.nextInt();
		while(t-->0) {
			int n = sc.nextInt();
			String str = sc.nextLine();
			boolean check = false;
			if(n>2) {
				for(int i=0; i<n-2; i++) {
					for(int j=i+2; j<n-1; j++) {
						if(i+1<n && j+1<n) //StringIndex Bound..additional if statement
							if(str.substring(i, 2) == str.substring(j,2)) {
								check = true;
			if(check) System.out.println("YES");
			else System.out.println("NO");
Updated 13-Dec-22 20:59pm

1 solution

The problem is simple: the string is not long enough for one of the substring operations to work.

The cause however, is more complex - and we can't fix it for you because it depends on the exact string and number you enter, and we have no access to those.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

What exactly is in str, n, i, and j when the substring fails? We can't tell, but when you know that, you can start looking at why it's wrong.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900