Search code examples
javaassignment-operatorarray-initialization

insert AssignmentOperator ArrayInitializer error


I am learning java but stuck with this issue, I am writing a simple code but this error is throwing up again Can some one help me with what wrong i am doing?

public String alarmClock(int day, boolean vacation) {
if (day >= 1 && day <= 5) {
  if (vacation = true) {
      return "10:00";
  }
  else (vacation = false) {return "7:00";}
 }
else {
  if (vacation = true) {
      return "off";
  }
  else (vacation = false) {return "10:00";}
 }
}

the error which it is giving is-

Error:  else (vacation = false) {return "7:00";}
                      ^
Syntax error, insert "AssignmentOperator ArrayInitializer" to complete ArrayInitializerAssignement

What the output i want is this -

alarmClock(1, false) → "7:00"
alarmClock(5, false) → "7:00"
alarmClock(0, false) → "10:00"

I know this may be simple but i am just new to java so i want to learn this.

Thanks in advance !


Solution

  • In a condition use == (comparison), not = (assignment) :

    change

    if (vacation = true)
    

    to

    if (vacation == true)
    

    or even better

        if (vacation)
    

    Beside that, else (vacation = false) is invalid syntax, and you don't need it anyway. Just write else.

    if (day >= 1 && day <= 5) {
      if (vacation) {
          return "10:00";
      } else {
          return "7:00";
      }
    } else {
      if (vacation) {
          return "off";
      } else {
          return "10:00";
      }
    }