0

this is my first post in here, btw, my teacher has given the class an assignment in programming in which we need to do a palindrome program, i'm able to do it but i wanted to get rid of the error, can you please explain me why there's an error, and how do I get rid of it?

import java.io.*;

public class AssignmentInCopro 

{public static void main (String [] args) throws IOException
    {BufferedReader x = new BufferedReader(new InputStreamReader(System.in));

    String word = "";

    System.out.print("Please enter the word you want to see in reverse: ");
    word = x.readLine();

    int wordLength = word.length(); 

    while (wordLength >=0)
    {
    char letter = word.charAt(wordLength - 1);
    System.out.print(letter);
    wordLength--;
    }
    }
}
1
  • 1
    Change the condition to wordLength > 0 (without the =). Commented Sep 7, 2014 at 8:18

3 Answers 3

1

The error comes while your loop includet the index zero. If the wordLength is zero so you will look for the charAt(-1) and you get the exception:

Change your code to:

while (wordLength >0)

And the error is gone.

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

Comments

0
 while (wordLength >=0)

this cause error when wordLength =0 then char letter = word.charAt(wordLength - 1); is actually char letter = word.charAt(0 - 1);

while (wordLength >0)

This should be condition or you can write your loop like this -

int wordLength = word.length() - 1;
while (wordLength >=0){
    System.out.print(word.charAt(wordLength--));
}

Comments

0

Look what happens when wordlength is actually equals to 0 //while (wordLength >=0) you trying to access char at -1 //word.charAt(wordLength - 1);

change it with while (wordLength >0) or while (wordLength >=1)

Have a nice day

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.