Serpantin Serpantin - 2 months ago 7
Java Question

Push in a Stack char-value have different value

everyone.
I need to put char-value in Stack:

for(char ch: operand.toCharArray()) {
System.out.println("ch: " + ch);
numericsOfTheOperand.push((int) ch);
System.out.println("numericsOfTheOperand.peek() " + numericsOfTheOperand.peek());
}


For example, operand: 456454
Output in console:

ch: 4
numericsOfTheOperand.peek() 52
ch: 5
numericsOfTheOperand.peek() 53
ch: 6
numericsOfTheOperand.peek() 54
ch: 4
numericsOfTheOperand.peek() 52
ch: 5
numericsOfTheOperand.peek() 53
ch: 4
numericsOfTheOperand.peek() 52
ch: 4
numericsOfTheOperand.peek() 52


I don't understand, why value is different?
How can I resolve it?

Answer

To push char to a Stack you will need to declare it as a:

Stack<Character> numericsOfTheOperand = new Stack<>();

And then you can do your thing:

String operand = "456454";
for(char ch: operand.toCharArray()) {
    numericsOfTheOperand.push(ch);
    System.out.println("numericsOfTheOperand.peek() " + numericsOfTheOperand.peek());
}

Out:

numericsOfTheOperand.peek() 4
numericsOfTheOperand.peek() 5
numericsOfTheOperand.peek() 6
numericsOfTheOperand.peek() 4
numericsOfTheOperand.peek() 5
numericsOfTheOperand.peek() 4

You were casting a char to int and thus getting the int value of it.

Comments