Best Fare Calculator

I am currently working on Best Fare Calculator and I am trying to create a constructor, but the problem is that there is always an error:

This is my code:

public class TransitCalculator{
  int days;
  int rides;
  String name;
  double price;
  public Transit(String transitName, double moneyRequired) {
    name = transitName;
    price = moneyRequired;
  }
  public double unlimited7Price(int day, int ride){
    if(day % 7 > 0){
      int week = day / 7 + 1;
    }
    return week * 33.00 / ride;
  }
  public static void main(String[] args){
    double[] ridePrices = new double[3];
    ridePrices[0] = 2.75;
    ridePrices[1] = 33.00;
    ridePrices[2] = 127.00;
    Transit("Pay-Per-Ride", 2.75) = new Transit();
  }
}

And here is the error:

TransitCalculator.java:6: error: invalid method declaration; return type required
  public Transit(String transitName, double moneyRequired) {

The clue is in the error message. The method declaration for Transit() is invalid. Specifically, it’s missing a return type.

Some examples of return types are int, double, string, void. If you don’t want to return anything with your method, use void.

I am not creating a method, I am creating a class constructor.

1 Like

Then I think you need to name it the same as your class. Check the docs to verify.

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

This will also throw an error:

Transit("Pay-Per-Ride", 2.75) = new Transit();

for java, object instantiation goes something like

ClassName instanceName = new ClassName(initializing parameter);
// for example:
Student bobCostas = new Student("Bob", "Costas");

more info on that in docs (https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html)


Moreover: java might have issues with this type of line, because of the conditional on the declaration.

public double unlimited7Price(int day, int ride){
    if(day % 7 > 0){
         int week = day / 7 + 1;
    }
    return week * 33.00 / ride;
}

Arguably, you don’t really need use use a week variable in this scenario, but if you did you’d have to revise the declaration.