Reputation: 7
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--;
}
}
}
Upvotes: 0
Views: 50
Reputation: 329
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
Upvotes: 0
Reputation: 41200
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--));
}
Upvotes: 0
Reputation: 69440
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.
Upvotes: 1