Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing words from an array in reverse

I have a task where I need to print words from an array in reverse(the word itself). This is what the task states :

  1. Create an array of words called ‘wordList’ and assign the values ‘Stressed’, ‘Parts’, ‘Straw’, ‘Keep’, ‘Wolf’

  2. Create a string called ‘reversedWord’ and do not assign it a value.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  3. Similar to the above challenge, however, instead of reversing a sentence, reverse the order of the letters

within each string.

a. You will need to create a for-loop to access each word in turn. Immediately within the loop set

‘reversedWord = “”;’

b. Then create another for-loop inside of the first one to iterate backwards through the current

word. Update the value of ‘reversedWord’ on each iteration.

c. Print the reversed word on the screen.

STRETCH CHALLENGE: Handle the word so that it reads properly backwards. (Stressed becomes Dessert)

I don’t know wether I’m just not understanding the wording of the task or not, but this is the code I have at the moment:

String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
String reversedWord;

for (int i = wordList.length; i >= 0; i++) {
    reversedWord = "";
    for (int j = wordList[i].length() - 1; i >= 0; j--) {
        reversedWord += wordList[i].charAt(j);
        System.out.println(reversedWord);
    }
}

It gives me this error when i run it:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at Main.main(Main.java:22)

Any help explanation would be helpful.

>Solution :

There are a few issues here. In the line

for (int i = wordList.length; i >= 0; i++) {

you are setting i to be the length of the wordList, which is 5. Remember, though, that array indexes start at 0. So the valid indexes of wordList are 0, 1, 2, 3, and 4, but not 5. To fix this, you can just subtract 1 from the length.

for (int i = wordList.length - 1; i >= 0; i++) {

The next problem is that you are increasing i at the end of each loop. Since it seems like you’re trying to iterate backwards, you’re gonna want to decrease i, not increase it.

for (int i = wordList.length - 1; i >= 0; i--) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading