Whibble
Whibble

Reputation: 3

If Else AssignmentOperator Issues - Java

I'm a beginning student in a Java class, so this will probably seem stupid to you guys. Here's the code.

class CyclingResult implements IEvent {
  double time;
  int finishOrder;

  CyclingResult(double time, int finishOrder) {
    this.time = time;
    this.finishOrder = finishOrder;
  }

  public double pointsEarned() {
    return if (this.finishOrder == 1) {
      (this.time - 10);
    } else if (this.finishOrder == 2) {
      (this.time - 7);
    } else if (this.finishOrder == 3) {
      (this.time - 3);
    } else {
      this.time;
    }
  }
}

I get a set of 5 "Error: Syntax error, insert "AssignmentOperator Expression" to complete Expression"

I'm sure it's something stupid going on with my code, but the examples I can find are a little above my head to figure out the differences.

Upvotes: 0

Views: 199

Answers (3)

Andy Turner
Andy Turner

Reputation: 140514

The closest to what you're trying to do here is a nested conditional operator:

return (this.finishOrder == 1) ? (this.time - 10)
     : (this.finishOrder == 2) ? (this.time - 7)
     : (this.finishOrder == 3) ? (this.time - 3)
     : this.time;

You can't use return if ... because if is a statement, not an expression.

Upvotes: 1

user7953963
user7953963

Reputation:

You're not returning the value properly. You must use return for each condition if you want to return the value immediately.

public double pointsEarned() {
    if (this.finishOrder == 1) {
        return (this.time - 10);
    } else if (this.finishOrder == 2) {
        return (this.time - 7);
    } else if (this.finishOrder == 3) {
        return (this.time - 3);
    }
    return this.time;
}

For multiple if/else-if statements you should consider using a switch statement:

public double pointsEarned() {
    switch (this.finishOrder) {
        case 1:
            return (this.time - 10);
        case 2:
            return (this.time - 7);
        case 3:
            return (this.time - 3);
        default:
            break;
    }
    return this.time;
}

Upvotes: 0

Joe C
Joe C

Reputation: 15714

You cannot return an if statement in Java. Unlike other languages (such as Scala), an if statement is exactly that: a statement (with no value).

You instead need to return inside each if/else block separately.

public double pointsEarned() {
    if (this.finishOrder == 1) {
      return (this.time - 10);
    } else if (this.finishOrder == 2) {
      return (this.time - 7);
    } else if (this.finishOrder == 3) {
      return (this.time - 3);
    } else {
      return this.time;
    }
  }

Upvotes: 4

Related Questions