2

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

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Paige
  • 159
  • 6

2 Answers2

3

You can convert it to String using String.valueOf.

operators.push(String.valueOf(operator));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

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

Rakib
  • 145
  • 13
  • No argument in my Stackoperators, so I changed my operator into a String but I would still have the same casting issue, e.g. String operator = ((String) line.charAt(i)); – Paige Oct 12 '21 at 18:37
  • 2
    The problem is in the right side of your equal sign. You cannot simply cast from one type to another for any random type. The target class you are trying to cast should be a subclass or implemented interface of the original class. You need to follow any of the valid methods from the suggested url to convert a char to a String. – Rakib Oct 12 '21 at 18:47