大家。 我需要将char值放在Stack中:
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
我不明白为什么价值不同? 我该如何解决?
答案 0 :(得分:0)
要将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
的价值。