2

I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is.

I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array.

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string to see it in reverse: ");
    String userEntry = sc.nextLine();
    char[] entryToChar = userEntry.toCharArray();
    System.out.println(Arrays.toString(entryToChar));
    String[] splitInput = userEntry.split(" "); 
    String reverseWord = "";
    int temp;
    String[] reverseString = new String[splitInput.length]; 

    for (int i = 0; i < splitInput.length; i++) 
    {
        String word = splitInput[i];            


        for (int j = word.length()-1; j >= 0; j--) 
        {
            reverseWord = reverseWord + word.charAt(j);
        }            

        for (int k = 0; k < splitInput.length; k++) {
                temp = splitInput[i];
                splitInput[i] = reverseWord[j];
                reverseWord[j] = temp;

                }

     }  System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);

I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below:

temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
4
  • If it doesn't compile, you should check the errors, the compiler shows you. At least post the errors here. Commented Jul 22, 2019 at 5:39
  • @Ridcully, this is where I get the compilation errors, but cannot find a way to fix them. I tried to do 'reverseString = reverseString + reverseWord[k], but it didn't work either. Commented Jul 22, 2019 at 5:45
  • There must be a lot of compilation errors. You've used wrong indexes in the loop as well. Commented Jul 22, 2019 at 5:51
  • What compiler errors exactly? Just copy them and paste them into your question. Commented Jul 22, 2019 at 7:03

8 Answers 8

2
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String word, reverseWord;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string to see it in reverse: ");
        String userEntry = sc.nextLine();

userEntry: I love you

        String[] splitInput = userEntry.split(" ");

splitInput: [I, love, you]

        for (int i = 0; i < splitInput.length; i++)
        {
            word = splitInput[i];
            reverseWord = "";
            for (int j = word.length()-1; j >= 0; j--)
            {
                reverseWord = reverseWord + word.charAt(j);
            }
            splitInput[i] = reverseWord;
        }

splitInput: [I, evol, uoy]

        System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
    }
}

Your string with words spelled backwards is: I evol uoy

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

2 Comments

thank you! That took care of the problem, and I leaned how to make code logic clearer. I feel almost dumb for forgetting about the String.join method, but I am a beginner learner afterall...
My pleasure @AnneBailly.
1

Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String.

The other problem is variable j is outside its block scope from where you are trying to access.

Make your logic clear before writing code to achieve correct result.

Comments

1

A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. I would suggest to use the class StringBuilder, which has a method for reversing the string. Your program could look like this:

while in.hasNext() {
  StringBuilder sb = in.next();
  sb.reverse();
  System.out.println(sb.toString());
}

If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse().

Please know that String in Java is an immutable object. You cannot modify it directly. You can have modified copies returned.
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above.

Comments

1

You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice.

class Testarray{
    public static void main(String args[]){
        String str = "I am Engineer";
        String[] spArray = str.split(" ");
        String farr[] = new String[spArray.length];

        for(int i=0;i<spArray.length;i++){
            String split = spArray[i];
            farr[i]=reverseString(split);
        }

        for(int i=0;i<farr.length;i++){
            System.out.println(farr[i]);
        }
    }
    public static String reverseString(String str){  
        char ch[]=str.toCharArray();  
        String rev="";  
        for(int i=ch.length-1;i>=0;i--){  
            rev+=ch[i];  
        }  
        return rev;  
    }  
}

Comments

0

There are a few things going on here, and I think in some places you're mixing up between strings and arrays.

Let's try to break this problem down into smaller problems.

First, we need to reverse a single word. Your first inner loop (the one that uses j) does that, so let's extract it into its own method:

public static String reverseWord(String word) {
    String reverseWord = "";
    for (int j = word.length()-1; j >= 0; j--) {
        reverseWord = reverseWord + word.charAt(j);
    }
    return reverseWord;
}

Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable):

public static String reverseWord(String word) {
    StringBuilder reverseWord = new StringBuilder(word.length());
    for (int j = word.length()-1; j >= 0; j--) {
        reverseWord = reverseWord.append(word.charAt(j));
    }
    return reverseWord.toString();
}

Once you have that, you can split the input string (like you did), revere each word, and join them back together:

Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");

for (int i = 0; i < splitInput.length; i++) {
    splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " + 
                   String.join(" ", splitInput));

Comments

0

All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse:

public static void main(String... args) {
    String str = getSentenceFromConsole();
    System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}

private static String getSentenceFromConsole() {
    try (Scanner scan = new Scanner(System.in)) {
        System.out.print("Enter a string to see it in reverse: ");
        return scan.nextLine();
    }
}

private static String reversLettersInWords(String str) {
    return Arrays.stream(str.split("\\s+"))
                 .map(word -> new StringBuilder(word).reverse().toString())
                 .collect(Collectors.joining(" "));
}

Comments

0

i try with your code

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string to see it in reverse: ");
    String userEntry = sc.nextLine();
    String[] splitInput = userEntry.split(" "); 
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < splitInput.length; i++) {
        String word = splitInput[i];
        for (int j = word.length() - 1; j >= 0; j--) {
            sb.append(word.charAt(j));
        }
        sb.append(" ");
    }
    System.out.println("Your sttring with words spelled backwards is " + sb.toString());

here i remove all access line of code....

4 Comments

Forget about string concatenation in the loop!
are you thinking reverseWord = reverseWord + word.charAt(j); this line in wrong...?
Yes + reverseWord = reverseWord + " "
but you know reverseWord = reverseWord + word.charAt(j); and reverseWord += word.charAt(j); both give same result....
-1
String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);

You can use this implementation to try to reverse the string elements in the array.

1 Comment

This will reverse the whole string, not the single words inside the string.

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.