1

I want to print the sentence with the characters of each word backwards.

Example: The fox jumped over the fence.

Becomes: ehT xof depmuj revo eht ecnef.

I can only reverse the first word, and then it gave me an ArrayIndexOutOfBoundsException.

Drews
  • 45
  • 1
  • 7

6 Answers6

4

Try following simple code. It is much easier:

String[] words = sentence.split(" ");
for (String word : words) {
    System.out.print(new StringBuilder(word).reverse() + " ");
}
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
Masudul
  • 21,823
  • 5
  • 43
  • 58
3

A few changes need to be done to you code:

1.change sentence.length() with words.length

2.use read.nextLine(); to get the sentence as input

try

import java.util.Scanner;
import java.util.Stack;

public class test {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in); // Error in line 11
        System.out.print("Enter a sentence: ");
        String sentence = read.nextLine();
        boolean containsPeriod= false;
        if (".".equals(sentence.substring(sentence.length()-1,sentence.length()))){
               sentence = sentence.substring(0,sentence.length()-1);
               containsPeriod=true;
           }


        String[] words = sentence.split(" ");
        for (int i = 0; i < words.length; i++) {
            String word = words[i]; // Error in line 23
            System.out.print(reverseWord(word));
            if(i!=words.length-1)
                System.out.print(" ");
        }
        if(containsPeriod)
            System.out.print(".");
        read.close();
    }

    private static String reverseWord(String sentence) {
        Stack<Character> rev = new Stack();
        for (int ii = 0; ii < sentence.length(); ii++) {
            rev.push(sentence.charAt(ii));
        }
        String out = "";
        while (rev.size() != 0) {
            out += rev.pop();
        }
        return out;
    }
}
upog
  • 4,965
  • 8
  • 42
  • 81
  • Is there a way I can get the period to remain at the end of a sentence? Somehow when I have the period at the end, the period was counted as part of the last word and so it was reversed together with the last word. – Drews Nov 03 '13 at 08:00
  • have made an update check now – upog Nov 03 '13 at 08:12
  • Sorry, but where exactly do I put the containsPeriod in? – Drews Nov 03 '13 at 13:55
  • updated code, check now – upog Nov 03 '13 at 14:05
  • Sorry for the trouble. It was actually the eclipse's fault when I put the containsPeriod in yesterday. It kept pop up the main exception and can't find source. Had to copy my original code from here and re-fix all the problems. – Drews Nov 03 '13 at 23:18
2

Replace sentence.length() with words.length in the first for loop.

You want to iterate this loop once per word in the sentence; but the code that you have written is iterating it once per letter in the sentence. That is your error.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
1

you can fix your code as shown below

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;

public class Query1 {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in); // Error in line 11

        System.out.print("Enter a sentence: ");
        // String sentence = read.next();
            // read full line here instead of just one word
        String sentence = read.nextLine();
        String[] words = sentence.split(" ");
            // this looks goes to array length
        // for (int i = 0; i < sentence.length(); i++) {
        for (int i = 0; i < words.length; i++) {
            String word = words[i]; // Error in line 23
            // System.out.println(reverseWord(word));
                    // use print not println
            System.out.print(reverseWord(word));
                    // this loop is not at all required
            // for (i = 0; i < words.length - 1; i++) {
            // System.out.println(" ");
            // }
            System.out.print(" ");
        }

    }

    private static String reverseWord(String sentence) {
        Deque<Character> rev = new ArrayDeque<Character>();
        // ArrayStack<Character> rev = new ArrayStack<Character>();

        for (int ii = 0; ii < sentence.length(); ii++) {
            rev.push(sentence.charAt(ii));
        }
        String out = "";
        while (rev.size() != 0) {
            out += rev.pop();

        }

        return out;
    }
}
Nitin Dandriyal
  • 1,559
  • 11
  • 20
0

Try this

public static void main(String args[]) {
        String input = "The fox jumped over the fence";
        StringBuilder sbReverseSentance = new StringBuilder();
        String words[] = input.split(" ");
        for (String word : words) {
            for (int i = word.length() - 1; i >= 0; i--) {
                sbReverseSentance.append(word.charAt(i));
            }
              sbReverseSentance.append(" ");
        }
        System.out.println (sbReverseSentance.toString());
    }
Shamse Alam
  • 1,285
  • 10
  • 21
0

Try this, it doesn't handle punctuation.

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    Scanner read = new Scanner(System.in);

    System.out.print("Enter a sentence: ");
    String sentence = read.nextLine();

    String[] words = sentence.split(" ");

    String[] reversed_words = new String[words.length];

    for (int i = 0; i < words.length; i++) {
        reversed_words[i] = reverseWord(words[i]);
    }

    for (int i = 0; i < reversed_words.length; i++)
        System.out.println(reversed_words[i]);

}

private static String reverseWord(String word) {
    String result = "";
    char[] array = word.toCharArray();
    for (int i = array.length - 1; i >= 0; i--) {
        result += array[i];
    }
    return result;
}
} 
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73