Simpler Method exercises with input parameters, return values and test cases:

Goal: create a method that returns a value and takes in a parameter. Use that method in a main routine. Create another method in the same class and use it in the same main routine. Then, add in user interaction. Then, use that method in a loop. Then accumulate some total inside the loop and print it at the end.

Create the following method:

 

Step I - create this method:

 

profitOnOneSale

Input parameters:

 

Double

Price

 

Double

Cost

Description of processing:

The profit is the price minus the cost.

Return:

 

Double

Profit

Now test this method:

Step II - code your main method to use this new method you created:

  1. Put the following in your main method:
  1. Run the program
  2. change the value of myprice to 30 and mycost to 60 and rerun it.

 

Step III - Create another method in your same class:

. profitOnManySales

Input parameters:

 

Double

Price

 

Double

Cost

 

Int

Quantity sold

Description of processing:

The profit is the price minus the cost. Multiply that times the quantity sold for the total profit.

Return:

 

Double

Profit

 

Now test this method:


Step IV: Change your main method to print a price on many sales

  1. Code the following:
    • After you tell the user the profit on one sale in your main method, do the following:
    • Create 2 new variables: int myquantity and set it to 3 AND double profitForQuantity and set it to 0
    • Calculate the profit they make when that quantity is sold. (For this exercise, you must use your profitOnManySales method to do that. )
      call the profitOnManySales method sending the price and cost and quantity. Be sure to save the answer into a variable
    • Tell the user : "By selling " + myquantity + " items, you made " + profitForQuantity + " total profit on this sale."

  1. Test your methd and then change the quantity to 5 and test it again.


Step V: Change your main method to ask for the quantity:

  1. After you tell the user the profit on one sale, ask them "How many did you sell in week 1?" and take in the answer.
Step VI: Change your main method to ask for 5 quantities, one for each week
    1. Change your program to ask for the quantity sold for each of 5 weeks. (Use a for loop to run 5 times)
    2. After each quantity tell them the total profit for that sale.
    3. When this is done test it.
    4. At the end of 5 weeks, tell the total profit.