【问题标题】:If statement comparing 2 conditions of ints runs as boolean比较整数的 2 个条件的 if 语句作为布尔值运行
【发布时间】:2018-05-16 06:58:26
【问题描述】:

我的 if 语句无法正常工作。目的是将用户给定的日期与当前日期进行比较,如果月份和星期都匹配(用户的生日),则 getBonus = true。 但是,我的 if 语句给了我以下错误:

二元运算符'&&'的错误操作数类型 第一种类型:int 第二种:int

不兼容的类型:int 不能转换为 boolean

当所有涉及的变量都是 int 时,为什么我的 if 语句试图作为布尔值运行?

public static boolean getBonus ( int Week, int Month, int bMonth, int bWeek 
) {

boolean getBonus = false;

/**************************************************************************
The following statement is used to determine if the user's birthday is 
this week, using the month and week of the month. bMonth/bWeek are generated 
from user input, Month/Week are generated from a real time calendar.
**************************************************************************/

if(bWeek = Week && bMonth = Month)
  {
    getBonus = true;

  }

return getBonus;
}//end class getBonus

【问题讨论】:

  • = vs ==...... 以拼写错误结束
  • 你可以简单地return bWeek == Week && bMonth == Month;(不需要if条件的局部变量getBonus)。

标签: java if-statement int boolean multiple-conditions


【解决方案1】:

使用If语句如下

if(bWeek == Week && bMonth == Month)
{
     getBonus = true;

 }

== 用于比较

= 用于赋值

【讨论】:

    【解决方案2】:

    这样做

     if(bWeek == Week && bMonth == Month)//used to compare 
     // true && true --> true
    

    不是这个

     if(bWeek = Week && bMonth = Month)//used to assign 
    

    【讨论】:

    • 这样更好,但不能修复不兼容的类型。
    • 它肯定会解决类型不兼容的问题,因为这是一个返回 truefalse 的比较。
    猜你喜欢
    • 2016-05-09
    • 2018-02-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2016-07-27
    • 2013-03-01
    相关资源
    最近更新 更多