Home > Back-end >  How to push a char into a String stack?
How to push a char into a String stack?

Time:10-13

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

CodePudding user response:

You can convert it to String using String.valueOf.

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

CodePudding user response:

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

  •  Tags:  
  • java
  • Related