0

I can never get this to loop all the way through the string. I can't use >= or == in this loop it stops it from working :( help

    int s = 0;
    String twocharacters = "";

    for (int i = 0; i < value.length(); i++){

        char c = value.charAt(i);
        char w = value.charAt(i + 1);

        if (c == '/' && w == '*' && s == 0){
            s = 1;
        }
        else if (c == '*' && w == '/' && s == 1){
            s = 0;
        }
        else if (s == 0 && c != ' ' && c != '*' && c != '/'){
            twocharacters += c;
            System.out.println(twocharacters);
        }
    }
4
  • Please explain what the "value" is Commented Dec 7, 2011 at 0:45
  • You'll also want to stop one character before the end because of the charAt(i + 1). Commented Dec 7, 2011 at 0:46
  • char w = value.charAt(i + 1) will lead to an exception when i == value.length() - 1 Commented Dec 7, 2011 at 0:46
  • if you want to do a charAt(i + 1), you should run the loop only till i < length -1. Commented Dec 7, 2011 at 0:48

1 Answer 1

3

At the last iteration (i = value.length() - 1), assigning value.charAt(i + 1); to w would throw an exception because you are at the end of the string and cannot get the next character.

Try:

for (int i = 0; i < value.length() - 1; i++){

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

Comments

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.