user3003049
user3003049

Reputation: 13

Java - calculating total with cost and unknown number of items

I have a task here: Define a class PayPerView with method moviefee() that calculates the monthly charges for movies rented. The method should take one argument representing number of movies rented and return the fee as a double.

The rental fee fee is $6.99 per movie. Preferred customers that rent more than 10 per month get a discount of 5%.

Here's my code so far:

public class PayPerView {

public static void main(String [] args){


}
public static double moviefee(int n){

    double fee = 6.99;
    double total= n*fee;

    System.out.println("Your balance due this month is" + total);   

    //return 6.99*n * ((n>10) ? 0.95:1);

}}

I know it's awful, I'm sorry and you can ignore that last line of code I commented out because I'm going to redo it and turn it into an if statement. I thought maybe I should use an array, but I can't right? Because I don't know how many movies are/will be rented? Should I use an arraylist for the number of movies rented?

Upvotes: 0

Views: 1737

Answers (3)

AAA
AAA

Reputation: 1384

I don't see why you'd use an ArrayList if you don't have any data to put into it.

You'd probably want to try something along these lines:

double total = n * fee;
if (n > 10) {
  total *= 0.95;
}

I also see that you wanted to use the ternary operator, so you could replace the above code block with

double total = n * fee * (n > 10 ? 0.95 : 1.0);

Upvotes: 0

Paperwaste
Paperwaste

Reputation: 685

Your on the right track

public static double moviefee(int n){

    double fee = 6.99;
    double total;
    if(n <= 10){
        total= n*fee;
    }
    else{
        total= n*fee - (n*fee*0.05); //5 percent discount
    }

    System.out.println("Your balance due this month is" + total);   

    return total;

}

Edit: added double total;

Upvotes: 0

Mumbleskates
Mumbleskates

Reputation: 1318

Actually that line you commented out looks pretty much exactly what you are trying to do anyway. Is there something particularly wrong with it?

If you really need to output the result on the console...

final double fee = 6.99;
double total = n * fee * (n > 10 ? .95 : 1.0);

System.out.println("Your balance due this month is" + total);

return total;

Upvotes: 1

Related Questions