Darrius
Darrius

Reputation: 177

Stack cannot push due to : String cannot be converted to char

import java.util.*;

public class plates2{
    private static Scanner in;
    private static Stack platestack = new Stack();

    public static void main(String[] args)
    {
        add();
    }

    public static void add()
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter plate: ");
        String pl = in.nextLine();

        System.out.println("Plate added! ");

        platestack.push(pl);
    }
}

So I cannot compile the code and gave me this error.

error: incompatible types: String cannot be converted to char platestack.push(pl);

Can someone please point out what's wrong? I want to push a string to the stack.

Upvotes: 0

Views: 173

Answers (2)

Stephen C
Stephen C

Reputation: 718788

When I compile this class (using Java 8), I do not get any error messages. I only get a warning about unsafe / unchecked operations.

But then you said you got this!

error: cannot infer type arguments for Stack private static Stack platestack = new Stack<>(); reason: cannot use '<>' with non-generic class Stack

>>Light-bulb moment<<

But java.util.Stack is a generic class. It has been since Java 5, when generics were introduced.

You must have defined your own Stack class, and you must be using it instead of the standard java.util.Stack. If you did that, and you defined the Stack.push operation to take (only) a char argument, then that would explain this compilation error. And it would also explain nobody else is seeing the compilation error.

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

Try defining your Stack to use strings with generics:

private static Stack<String> platestack = new Stack<>();

Upvotes: 0

Related Questions