Reputation: 27
I am trying to get the user to insert a string of at least 3 characters and if its even the program prints the first half, and if it is odd the program prints the middle 3. I keep receiving this error when I put in anything more than 3 characters.
import java.util.Scanner;
public class Stringex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a string at least 3 characters long ");
String a = input.nextLine();
int numberofletters = a.length();
if (numberofletters < 3) {
System.out.print("Sorry the string you entered is not long enough");
}
else if (numberofletters%2 == 0) {
System.out.print(a.substring(0, numberofletters/2));
}
else {
System.out.print(a.substring(numberofletters/2 - 1, numberofletters +2 ));
}
}
}
Upvotes: 0
Views: 63
Reputation: 77
As mentioned in a comment your issue is with this statement:
else {
System.out.print(a.substring(numberofletters/2 - 1, numberofletters +2 ));
}
Looking at the documentation for subString you can see the issue is with the endIndex you are passing in. Since numberofletters
refers to the length of your string, adding 2 to it will always index past the end of the string.
The documentation also helpfully shows what exceptions subString can throw and in what circumstance :
Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
[Emphasis mine]
Upvotes: 2