Home > Blockchain >  Printing words from an array in reverse
Printing words from an array in reverse

Time:04-25

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.

  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.

CodePudding user response:

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--) {

CodePudding user response:

There is a simpler solution using Java's StringBuilder class:

public static void main(String[] args) {
    String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
    for (int i = 0; i < wordList.length; i  ) {
        String word = wordList[i]; // Get the word from array
        word = new StringBuilder(word).reverse().toString(); // use StringBuilder to reverse the word
        wordList[i] = word; // put word back in the array
    }        
    System.out.println(Arrays.asList(wordList));
}

This outputs

[dessertS, straP, wartS, peeK, floW]

UPDATE: For the words to read properly (first character in uppercase), You could do something like this:

word = word.toLowerCase();
word = word.replace(word.substring(0,1), word.substring(0,1).toUpperCase());
wordList[i] = word; // put word back in the array

There are more effective ways to do this, but is simpler for you to understand. This obviously outputs:

[Desserts, Strap, Warts, Peek, Flow]

substring(0,1) returns the first character (substring from index 0 to index 1; where the last index is not inclusive) as a String. Then, you are replacing the same substring with the uppercase substring.

  • Related