Home > OS >  Reversing the order of a string in Java [duplicate]
Reversing the order of a string in Java [duplicate]

Time:10-07

public static void main (String[] args) {
    // get string from user
   String input = ValidatedInputReader.getString("Enter a sentence.", "");
   // split string into words
   String[] splitInput = input.split(" "); 
   Stack stack = new Stack();
   String[] reverseInput = new String[input.length()];
   
   // push the character into the Stack
   for (String i:splitInput){
       stack.push(i);
    }
   
   int i = 0;
    while (!stack.isEmpty()) { // popping element until
                               // stack become empty
                                // get the string from the top of the stack
        reverseInput[i  ] = stack.pop();
    }
    
    System.out.print(reverseInput);
 

}

I am trying to create a code that will read a string given by the user in reverse order using stacks. I was fairly certain this would work, but I am getting a "incompatible types" error on the reverseInput[i ] = stack.pop(); line. Does anyone know why this is happening and how to fix my code? Am I going about this wrong? I am stumped.

CodePudding user response:

I assume this is the error you are running into:

Error:(21, 42) java: incompatible types: java.lang.Object cannot be converted to java.lang.String

This of course states that you are attempting to convert an object of type Object into a String. The reason for this is that Stack is a generic class, allowing you to pass a type Parameter. The type parameter in this case decides what type of object the Stack will hold. In your case, you'd like the Stack to hold variables of type String.

However, because you did not supply a type parameter the program defaulted the type parameter to Object. When you attempted to pop(), the Stack returns an object of type Object, and thus when you try to assign this Object to an element of your String array, the compiler complains. Simply replace this

Stack stack = new Stack();

with below to assign the Stack a parameterized type of String. The <> signify that you are declaring a Generic Objects' type parameter.

Stack<String> stack = new Stack<>();

(I removed line 3 with a hardcoded input, I do not know what ValidatedInputReaderIs)

CodePudding user response:

Stack stack = new Stack();

should be

Stack<String> stack = new Stack<String>();

Also, check the reverseInput array's length.

  • Related