[英]Storing an int into a char array
I have these set up at the top of the method.我在方法的顶部设置了这些。
public static String eval(char[] postfix) {
StackInterface<Character> stack = new LinkedStack<>();
char[] answer = new char[postfix.length];
int numOne = 0;
int numTwo = 0;
int result = 0;
int i;
for (i=0; i < postfix.length; i++)
.....
Down the line I have done this:我已经做到了这一点:
if (!stack.empty()) {
numOne = stack.top();
stack.pop();
numTwo = stack.peek();
stack.pop();
//My problem is here. I can't push the result to my char[] array.
if (postfix[i] == '+') {
result = numOne + numTwo;
stack.push(result);
..........
How do I set it up so that I can push the result of the two pop()
'd variables to my char[]
array?我如何设置它以便我可以将两个pop()
变量的结果推送到我的char[]
数组?
You need too read them as Character (or char), not int; 您也需要将它们读为Character(或char),而不是int; The stack is working with Character, there is no reason to read the values into integer. 堆栈正在处理Character,因此没有理由将值读取为整数。 Like: 喜欢:
char numOne = 0;
char numTwo = 0;
char result = 0;
...
result = numOne + numTwo;
stack.push(result);
Note, there could be additional problem with the char range of the sum result. 注意,求和结果的char范围可能存在其他问题。
You should cast the result to a char, because if you use the method stack.push(int)
, the int will not be converted automatically. 您应该将结果stack.push(int)
转换为char,因为如果使用方法stack.push(int)
,则不会自动转换int。 Instead do this: stack.push( (char) result ); 而是这样做:stack.push((char)result); The result will be casted to a char. 结果将被强制转换为char。 Assigning an int value to a char is valid, because while assigning it, Java automatically casts it.But if you use an int as argument of a method instead of a char, Java wouldn't do that.Sorry for bad English, but more easily: Working: 为char分配一个int值是有效的,因为Java在分配它时会自动强制转换它。但是如果使用int作为方法的参数而不是char的话,Java不会这样做。对不起,英语不好,但是更多轻松: 工作:
char c = 364; //the int value is automatically converted
Not working 不工作
public void doSomething(char c) {..}
doSomething(534); //here the int will NOT be automatically casted to an int
Second example in a valid way 有效的第二个例子
doSomething( (char) 534);
In less words, you should push a casted int. 简而言之,您应该推送一个强制转换的int。 The (char)
is your friend (char)
是你的朋友
Note: you can encounter failures if the sum between the two ints is higher than the maximum char value available. 注意:如果两个int之间的总和高于可用的最大char值,则可能会遇到故障。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.