Paige
Paige

Reputation: 169

How to push a char into a String stack?

I'm trying to push certain characters into a stack given:

public static double infixEvaluator(String line)
public static final String SPECIAL_CHARACTER = "()+-*/^";
Stack<String> operators = new Stack<String>();

I assumed I would run through the String with a for loop, then use if statements that would check whether the char at the index was a special character or a regular number

else if (SPECIAL_CHARACTER.contains(line)) {
        char operator = line.charAt(i); 
        operators.push((String) operator);
}

Using this example: is there a way to add characters to a stack?

But I'm getting an error

cannot cast from char to string

I'm confused on why it's not allowing it to cast it?

if more code is needed let me know

Upvotes: 2

Views: 1245

Answers (2)

Rakib
Rakib

Reputation: 145

Use like operators.push(new String(new char[]{operator}));

The thing is char is a primitive data type where String is an object that is composed from a collection of chars. The concept of casting cannot be applied here rather you need to create a new String object using the char

There is also a lot of other different ways to convert a char to a String in the following answer.

https://stackoverflow.com/a/15633542/2100051

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89234

You can convert it to String using String.valueOf.

operators.push(String.valueOf(operator));

Upvotes: 3

Related Questions