views:

193

answers:

1

I have the following code in Java (which worked just fine in C++ for some reason) which produces an error:

int a;
System.out.println("String length: " + input.length());
for(a = 0; ((a + 1) * 97) < input.length(); a++) {
    System.out.print("Substring at " + a + ": ");
    System.out.println(input.substring(a * 97, 97));
    //other code here...
}

Output:

String length: 340
Substring at 0: HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHe
Substring at 1: 
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: -97
//long list of "at ..." stuff
Substring at 2: 

Using a string of length 200, however, the following output is produced:

String length: 200
Substring at 0: HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHe
Substring at 1: 

That is it; no exceptions raised, just... nothing. What is happening here?

+4  A: 

The second parameter to String.substring is the last index not the length of the substring. So you want the following (I assume):

int a;
System.out.println("String length: " + input.length());
for(a = 0; ((a + 1) * 97) < input.length(); a++) {
    System.out.print("Substring at " + a + ": ");
    System.out.println(input.substring(a * 97, (a + 1) * 97));
    //other code here...
}
Dean Harding
Yes, that was it! Thank you! Things are a bit different from C++ :)
wrongusername