Method exercises Without IF
Setup Create one new project to hold all of these. In that project, create an empty class called WorkIt to hold all of your methods.
First problem 1. ProfitOnOneSale
ProfitOnOneSale Step 1: Write the comment for your method Open the class Locate the curly brace that closed the last method. If it is the first, it should go right after the open curly brace for the class. Write the comments: public class WorkIt { /** * profitOnOneSale : Calculate profit on one sale * given the cost and price * @param double price - the price that comes in; * double cost – the cost that comes in * @return double profit – price minus cost */ }
ProfitOnOneSale – Step 2 Step 2 – write the method header Under the bracket, or after the end of another method, write “public static” Write the type of your result (ex: int). If it returns nothing, write “void”. Write the name of your method Between parentheses, write the type of your input followed by the name of the variable your method will use. If you have more than one, separate by commas. Every variable needs a type before it. Type an open and close curly brace.
ProfitOnOneSale – Step 2 Result public class WorkIt { /** * profitOnOneSale : Calculate profit on one sale * given the cost and price * @param double price - the price that comes in; * double cost – the cost that comes in * @return double profit – price minus cost */ public static double profitOnOneSale (double price, double cost) }
ProfitOnOneSale – Step 3 Step 3 – Send back a dummy result so it will compile Type return Type a value that would be valid for the return type. Type a semicolon Compile to see no errors. Ex: return 3;
Step 4 – write the test case Step 4 – write the test case in the comments Right below the comments about the method, add comments to list the test cases you will try and what the result should be.
Step 4 result public class WorkIt { /** * profitOnOneSale : Calculate profit on one sale * given the cost and price * profitOnOneSale(6,2.5)== 3.5 * profitOnOneSale(2,3) == -1.0 * profitOnOneSale(6.5,0) == 6.5
Step 5 – code inside the method Knowing you have a box in memory for every input variable already, code inside the method’s curly braces so that the proper return value will be sent back. This is very specific to every type of problem. Compile
Step 5 result public class WorkIt { /** * ProfitOnOneSale : Calculate profit on one sale * given the cost and price * @param double price - the price that comes in; * double cost – the cost that comes in * @return double profit – price minus cost */ public static double profitOnOneSale (double price, double cost) return price - cost; }
Step 6 – test it Compile and run your method. Run it for each of your test cases listed in the comments (Step 4) and compare to your expected results.