【问题标题】:How can i see if they are of the same type我如何查看它们是否属于同一类型
【发布时间】:2014-12-26 20:16:42
【问题描述】:
private static void ParseInput(String str) 
    {
        char c ;
        Integing item1;
        boolean result;
        int n =str.length();
        Stack StItem = new Stack(n);
        Queue QItem = new Queue(n);
        for (int i=0; i<n; i++){
            c = str.charAt(i);
            if ((c == '(') || (c=='[') || (c=='{')){
                Integing item = new Integing(i,c);
                StItem.push(item); 
            }else if((c==')') || (c==']') || (c=='}')){
                item1 = StItem.pop();               
                result = item1.getChar().class ==(c.class); //where i do the check
                if (result ){                     
                    Pair pair1 = new Pair(item1.getNumber(),i);
                    QItem.put(pair1);
                }else{
                    System.out.println("Syntax error");
                    System.exit(-1);
                }
            }
        }           
    }



public class Integing
{
    private int num;
    private char par;

    public  Integing(int numb,char paren)
    {
        num = numb;
        par = paren;
    }

    public  char getChar(){
        return this.par;   //The method i use to get the exact type
    }

    public  int getNumber(){
        return this.num;
    }

}

我想检查 item1 和 c 是否属于同一类型。实际上我使用了一个方法 getChar() 来 拿我想检查的东西。我在互联网上找到了getClass或class方法。当我 使用 getClass 我有取消引用错误,当我使用类时我有这些错误。

![1]:http://i.stack.imgur.com/1kQZg.png

【问题讨论】:

  • 请将您的错误粘贴为文本,而不是图像。反正 c 和 item1.par 都是字符,怎么可能是不同的类型呢?
  • 看看here。您不能在 chars 上调用 getClass,因为 char 是原始类型。再说一遍,反正这里也没用。
  • 我的作业说 item1.par 是一个左括号,因为它是从 StItem 中提取的,所以我应该检查它是否与 c 相同。谢谢你的链接 :)

标签: java comparison dereference


【解决方案1】:

我认为您正在寻找的是 instanceof,格式如下:

Boolean isChar = item instanceof Character;

这里有一些关于使用的文档:http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm

不过,我对您到底想要做什么感到有些困惑 - 虽然 instanceof 实现了您使用 .class 实现的功能,但我看不出它如何在您的代码上下文中帮助您。

【讨论】:

  • 感谢您的链接,毕竟我的代码中确实不需要比较。尽管,您的建议可能会帮助其他人比较 char,因为它是一个原始类并且 .getClass 不起作用! :)
猜你喜欢
  • 2023-04-09
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
相关资源
最近更新 更多