【问题标题】:Incompatible conditional operand types double and double Java(16777232) when using instanceof使用 instanceof 时不兼容的条件操作数类型 double 和 double Java(16777232)
【发布时间】:2021-12-28 02:57:57
【问题描述】:

我一直在从事一个个人 Java 项目,该项目本质上是在模仿一个常见的交易回测电子表格。在一行中使用多个 instanceof 运算符之前,一切都很好。我在网上看了看,但无济于事,没有发现任何相关的东西。在比较 double 类型和 int 时,我收到一个不兼容的条件操作数,但是字符串很好。我使用的编辑器是 VSCode。代码如下

            while (newLogBool){
            Scanner newLog = new Scanner(System.in);
            String nLPair = newLog.nextLine();
            double nLStartingBalance = newLog.nextDouble();
            int nLRisk = newLog.nextInt();

            try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }

            if ((nLPair instanceof String) && (nLStartingBalance instanceof double) && (nLRisk instanceof int)){
                Logger logger = new Logger(nLPair, nLStartingBalance, nLRisk);
                newLogBool = false;
            } else {
                System.out.println("Inccorect Type: Pair, Starting Balance or Risk. Please try again.");
            }
        }

谢谢

【问题讨论】:

  • 您只能将instanceof 用于非原始类型,即类。 String 是一个类,而 doubleint 都是原语。根本不需要那个检查,删除它。 nLPair 只能是String(甚至不能是子类,因为Stringfinal),nLStartingBalance 只能是double,而nLRisk 只能是int
  • 这已解决,谢谢!我只是想检查输入是否是有效的数据类型。
  • 检查数据类型已经通过Scanner的方法完成。如果输入不是双精度,则对 nextDouble() 的调用将引发异常。您不能将非双精度数挤入双精度数,这使得检查无关紧要。
  • 我不知道这个。感谢帮助,下次我会更彻底地阅读文档

标签: java instanceof


【解决方案1】:

instanceof 运算符只能应用于引用类型(或 null)。 doubleint 是原始类型,而不是引用类型。

Java Language Specification, 15.20.02

例如,在您的情况下,intint 的一个实例,不能是其他情况。所以没有必要问那个特定的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2019-07-11
    • 1970-01-01
    • 2016-04-16
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多