2

I'm learning Java and I don't know what is wrong here. Why is this error happening? I don't see anything wrong and that was actually working until when I wrote the line "count = 0" before the second "for" loop.

That is the error: java.lang.StringIndexOutOfBoundsException: String index out of range: 1

That's the line where the error is happening:

if(mots.get(j).startsWith(searchPhrase.substring(0,1))){

Here is the entire code:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        List<String> mots = new ArrayList<>();
        List<String> saida = new ArrayList<>();
        mots.add("un");
        mots.add("deux");
        mots.add("trois");
        String searchPhrase = "aaasdeuxctsundesle";
        int count = 0;
        int countAnula = 0;
        int azul = 0;
        String anula = "-"; //Tem que fazer cast para char depois
        String frase = searchPhrase;
        for (int i = 0; i < frase.length(); i++) {
            count = 0;
            for (int j = 0; j < mots.size(); j++) {
                if (mots.get(j).startsWith(searchPhrase.substring(0,1))) {
                    for (int t = 0; t < mots.get(j).length(); t++) {
                        if (searchPhrase.charAt(t) == mots.get(j).charAt(t)) {
                            azul ++;
                        } else {
                            break;
                        }
                    }
                    if (azul == mots.get(j).length()) {
                        saida.add(mots.get(j)); 
                        searchPhrase = searchPhrase.substring(mots.get(j).length());
                        j = 0;
                        azul = 0;
                    } else {
                        searchPhrase = searchPhrase.substring(1);
                        saida.add(anula);
                        j = 0;
                        azul = 0;
                    }
                } else {
                    count ++;
                }        
            } 
            if (count == mots.size()) {
                searchPhrase = searchPhrase.substring(1);
                saida.add(anula);
                count = 0;
            }   
        }
        for (int g = 0; g < saida.size(); g++) {
            System.out.println(saida.get(g)); 
        }
    }
}
6
  • 6
    Step through the code using your debugger and you should be able to find the problem. This is a key skill that every programmer is expected to be good at, and this is the perfect time for you to start learning it. Good luck :) Commented Nov 16, 2015 at 2:50
  • 3
    I have been trying for the past hour. Will keep trying though. Commented Nov 16, 2015 at 2:56
  • 2
    @IanPierre try breaking this into methods. There are refactoring tools (ex. Extract Method) in Eclipse and IntelliJ IDEA that make this easy. Commented Nov 16, 2015 at 3:03
  • 2
    @IanPierre I love that you are using interfaces out of the gate. Bravo. I see people miss this in paid work so you are already on your way to being a true software craftsman :) Commented Nov 16, 2015 at 3:07
  • 2
    It feels good to hear that, guys. Thank you! Commented Nov 16, 2015 at 3:33

2 Answers 2

12

First of all, congrats on getting started on Java. It's an amazing language and the possibilities are endless. Here is how you can go about fixing your error.

The first step is to understand exactly what your error means, so let's get to that!

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

The type of exception thrown is a StringIndexOutOfBoundsException. Anytime you get an IndexOutOfBoundsException (or any type thereof) it means that you are trying to access an index in an array that doesn't exist. By calling the substring method, you are dividing the string in a character array, and selecting characters A to B (In your case 0 to 1). If character 1 doesn't exist, and yet you try to access it, it will throw this error.

The reason you are getting this error is therefore that you are trying to execute a substring(0,1) on a String with less than 1 character, aka an empty string or even a null string maybe.

Also, to give you a quick tip. Typically, a you should create a new method if your method body extends 12 lines. This will hugely increase the readability of your code. It took me a while to find the right place for your fix :-)

Change

if (mots.get(j).startsWith(searchPhrase.substring(0, 1))) {

to

if (searchPhrase != null && searchPhrase.length() > 0 && mots.get(j).startsWith(searchPhrase.substring(0, 1))) {

By doing this you check if the length of your string is sufficient before executing the substring method

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the amazing answer. I wanna be a Mobile Developer, so JAVA is really important. I understand (by reading both you answer and Tsung-Ting Kuo answer) what is my error. It's not my real code, I'm just trying to figure out a part of a bigger work. Thanks again for your wonderful reply.
1

As @ray said, checking the exception message shows that the problem occurs while searchPhrase is an empty string. In this case, we try to ask for a substring(0, 1) from an empty string with size = 0, so we would get a StringIndexOutOfBoundsException. To avoid this, we can first check and confirm that the size of searchPhrase is > 0.

Therefore, a quick fix is to replace the line if (mots.get(j).startsWith(searchPhrase.substring(0, 1))) { to if (searchPhrase.length() > 0 && mots.get(j).startsWith(searchPhrase.substring(0, 1))) {.

Similarly, you might want to change if (count == mots.size()) { to if (searchPhrase.length() > 0 && count == mots.size()) {.

I have modified the above two lines and can run the code without exception. The output is:

-
-
-
-
deux
-
-
-
un
-
-
-
-
-

7 Comments

@IanPierre Sure, I have modified my answer. Please kindly take a look and see if this make sense. Thanks!
I added some letters in my String searchPhrase and I'm getting the same error message in some other line. (even if I add the searchPhrase.length() > 0 &&)
here is the line:if (searchPhrase.charAt(t) == mots.get(j).charAt(t)){
Even if I change the characters of the String (keeping the same length) I get this error.
I think I know what is going on. The searchPhrase will have fewer characters than the string in my ArrayList while the program is running. I will have to figure out a way fix this up.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.