【问题标题】:Infix to postfix evaluation后缀评估的中缀
【发布时间】:2018-03-12 12:26:45
【问题描述】:

如何将 char 转换为 Integer 类型?

int p2 = (int)stack2.pop();     
int p1 = (int)stack2.pop();       
int res = result(p2, p1, calStr.charAt(i));   

stack2.push(res);

我做了上面的方法,但是得到了一个runtime error,不能把java.lang.Character转换成java.lang.Integer

线程中的异常 "main" java.lang.ClassCastException:
java.lang.Character 无法转换为 java.lang.Integer

【问题讨论】:

  • stack2 真的是Stack<Character> 吗?如果是,为什么?
  • 为什么要在这里将char 转换为int?您是否想问如何将单个数字(例如'2')转换为数字(例如2),然后使用Character.digit(ch, 10),但您真的只支持一位数字吗?在您的表达式评估器中?堆栈上的值不应该已经一个数字吗?
  • 我使用 stack2 作为整数堆栈。我使用字符串来读取用户的中缀表达式,后缀表达式也是字符串的形式。但是当我尝试将特定索引处的 char 类型转换为 Int 时,它会给我运行时错误
  • 那么是calStr.charAt(i) 失败了吗?
  • no 错误显示在 int p2 =(int)stack2.pop(); int p1= (int)stack2.pop();我得到了 ASCII 数字的结果。(p1,p2 存储了 stack2.pop() 的 ASCII 数字。我使用了 int n= p2 - '0';

标签: java casting type-conversion


【解决方案1】:

说明

您不能直接将Character 转换为Integer,它们是对象。它们之间的转换只有在我们谈论 数据类型 charint 时才有效。

虽然 Java 确实 auto-boxes-unboxes IntegerintCharacterchar,反之亦然,但它不会自动使用这种技术可以在IntegerCharacter 之间进行快速转换。


解决方案

当然,您可以进行如下转换:

Character -> char -> int -> Integer

所以代码看起来像这样:

Character itemAsCharacter = stack2.pop();
char itemAsChar = itemAsCharacter.charValue();
int itemAsInt = (int) itemAsChar;
Integer itemAsInteger = Integer.valueOf(itemAsInt);

简而言之:

// Last step uses the implicit auto-boxing of int -> Integer
Integer item = (int) stack2.pop().charValue();

向后的方向类似:

Integer resultAsInt = ...
Character result = (char) resultAsInt.intValue();

stack2.push(result);

注意

请注意,StackVector 类在 Java 中都是过时的类。有些类具有相同的功能,提供更多的方法,更健壮,更简单。 LIFO 数据结构的示例列在接口Deque 下,最常用的实现是LinkedList,还有一个数组变体ArrayDeque

这是documentation of Stack的相关摘录:

一组更完整和一致的 LIFO 堆栈操作是 由 Deque 接口及其实现提供,应该 优先使用此类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-21
    • 2012-03-10
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多