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

2 Answers 2

3

You can convert it to String using String.valueOf.

operators.push(String.valueOf(operator));
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

No argument in my Stack<String>operators, 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));
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.