【问题标题】:When compiling code I get the bad operand error编译代码时出现错误的操作数错误
【发布时间】:2016-03-16 04:25:40
【问题描述】:

每次我尝试编译我的代码时,都会收到涉及布尔和 int 数组的“错误操作数”错误。任何帮助,将不胜感激。谢谢!

System.out.println("Passed: " + passed); 

if (exam.totalIncorrect() > 0)
{
    System.out.println("The incorrect answers are: "); 

    int missedIndex; 

    for (int i = 0; i < exam.totalIncorrect(); i++)
    {
        missedIndex = exam.questionsMissed()[i]+1; 
        System.out.print(" " + missedIndex); 
    }
}

我得到的错误是这样的:

   DriverExamApplication.java:58: error: bad operand types for binary operator   
   '+'   
            missedIndex = exam.questionsMissed() [i] +1; 

                                         ^

first type:  boolean

second type: int

【问题讨论】:

  • 问题在于尝试将布尔值添加到整数。您能告诉我missedIndex = exam.questionsMissed()[i]+1; 背后的想法吗?
  • 每次你尝试编译你的代码你都会得到这个编译错误。编译前不能运行。

标签: java arrays compiler-errors boolean


【解决方案1】:

您正在尝试添加一个带有整数的布尔值......

直接打印,节省转换类型的时间

System.out.print(" " + exam.questionsMissed()[i]+i+1);

【讨论】:

  • 对不起,我是编程新手。因此,[i] + 1 无效。我可以删除添加的内容吗?
  • 感谢您的回复。对不起,新手的问题。我绝对是一个试图自学编程的初学者。更改效果很好。
  • 当我运行我的代码时,一切都运行良好,但输出显示为您给我的代码段中的“false1 false1 false1”。它应该在数组列表中显示错误的问题编号。
  • 是的...打印 i+1 而不是 1...我刚刚更新了我的答案
【解决方案2】:

看起来exam.questionsMissed() 返回一个布尔数组。然后exam.questionsMissed()[i] 是布尔值,您正在尝试将 1 附加到它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2020-12-03
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多