大家。 我需要将字符值放入堆栈中:
for(char ch: operand.toCharArray()) {
System.out.println("ch: " + ch);
numericsOfTheOperand.push((int) ch);
System.out.println("numericsOfTheOperand.peek() " + numericsOfTheOperand.peek());
}
例如,操作数:456454 控制台输出:
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
我不明白,为什么值不同? 我该如何解决?
最佳答案
要将 char
推送到 Stack
,您需要将其声明为:
Stack<Character> numericsOfTheOperand = new Stack<>();
然后你就可以做你的事情了:
String operand = "456454";
for(char ch: operand.toCharArray()) {
numericsOfTheOperand.push(ch);
System.out.println("numericsOfTheOperand.peek() " + numericsOfTheOperand.peek());
}
输出:
numericsOfTheOperand.peek() 4
numericsOfTheOperand.peek() 5
numericsOfTheOperand.peek() 6
numericsOfTheOperand.peek() 4
numericsOfTheOperand.peek() 5
numericsOfTheOperand.peek() 4
您将 char
转换为 int
,从而获得它的 int
值。
关于java - 压入堆栈的字符值具有不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551592/