WHAT YOU WILL MAKE
Making a Practice Injury Calculator
Can use parameters to feed data into methods; can use return to bring results back to the caller; can write boolean query methods and understand overloading; and finally complete a damage calculator that considers weapons, sharpness, critical hits, and armor. Prerequisites: static methods will be defined and called. The recipe card in the previous lesson only had fixed materials; in this lesson, it is equipped with a material slot and a finished product outlet.
Before you start: It is recommended to complete Lesson 12 first
- Actual parametersProvide this material
- MethodCalculated by contract
- Return valueThe caller receives the result
01 / 15
Before you begin: Put the examples in the right place
This chapter uses JDK 21 and does not require the preview function. A complete program is given for each common example, saved with annotated file names. Multiple examples are placed in their own folders to avoid auxiliary classes with the same name.
Terminal command: Replace the Chinese placeholder with the actual name
javac -encoding UTF-8 ExampleFile.java
java ExampleClassClass names are case-sensitive. If the complete challenge code is divided into multiple sections, please connect them in the same file in order. Do not create separate classes for the continued sections. Run verification only lists the program output; additional input sequences are provided where input is required.
02 / 15
Enchanting table does not accept telepathy
The enchanter asked: "How much is the basic damage? How sharp is it? Is it a critical hit this time?" The player replied: "Guess." The enchanter closed the book: the method is not telepathic.
The parameters are the material slots in the method definition, and the actual parameters are the data actually put in when calling. The return value is the finished product handed over after the method completes the calculation.
- baseBasic damage, double
- sharpSharpness level, int
- criticalCritical hit status, boolean
- armorTarget armor, double
Starting with four questions
- Where do formal parameters and actual parameters appear respectively?
- Why must multiple parameters be passed in order?
- What is the difference between void and methods with return values?
- Why can't overloading just change the return type?
03 / 15
Parameter slot and actual parameter material
double base and int level are formal parameters; 7.0 and 3 are actual parameters. When the call occurs, the actual parameter values are entered into the corresponding parameters.
- Actual parametersValue provided at call location
- Shape participates in calculationMethod uses a copy of the value
- returnReturn the result to the calling place
L13Example02.java · Complete independent example
public class L13Example02 {
static double damage(double base, int level) { return base + level * 1.5; }
public static void main(String[] args) {
System.out.println(damage(7.0, 3));
System.out.println(damage(5.0, 0));
System.out.println(damage(8.0, 2));
}
}Output
11.5
5.0
11.004 / 15
Multiple parameters cannot be placed in the wrong format
If the two parameter types are the same, Java may still compile after passing them reversely. The house will change from 9×7 to 7×9, and then you can confidently say that you did not report an error.
- widthThe first item, horizontal width
- heightSecond item, vertical height
- Correct call9,7 gets width 9 height 7
- Transmission7,9 can be compiled but the meaning changes
L13Example03.java · Complete independent example
public class L13Example03 {
static void describeArea(int width, int height) {
System.out.println(width + " x " + height);
}
public static void main(String[] args) {
int houseWidth = 9, houseHeight = 7;
describeArea(houseWidth, houseHeight);
describeArea(houseHeight, houseWidth);
}
}Output
9 x 7
7 x 9Call Check
- When there are too many parameters, each actual parameter should be on a separate line.
- Use variable names with clear meanings and do not pile numbers directly.
- Test values with different width and height, and it is easier to see when the reverse is passed.
05 / 15
return Send the result back
The method with a return value is like a workbench: put in the materials and take out the finished products. Once return is executed, the method ends immediately and the value is handed to the caller. In this example, each material is limited to 0 to 64; returning 0 for illegal input is a convention of this method, and it is not a strategy that should be adopted by all calculation methods.
- Actual parametersValue provided at call location
- Shape participates in calculationMethod uses a copy of the value
- returnReturn the result to the calling place
L13Example04.java · Complete independent example
public class L13Example04 {
static int torchCount(int coal, int sticks) {
if (coal < 0 || sticks < 0 || coal > 64 || sticks > 64) return 0;
return Math.min(coal, sticks) * 4;
}
public static void main(String[] args) {
int torches = torchCount(7, 10);
System.out.println(torches);
System.out.println(torchCount(2, 5) >= 8);
}
}Output
28
true06 / 15
Return in advance to guard the boundary
Boundary checking is placed at the beginning of the method to keep the normal formulas that follow clear. Returning early is not skipping class, but the security guard asking the negative creeper to leave the workbench.
- Negative quantityReturn 0 directly
- Normal quantityCalculated by formula
- Oversize materialThis example is also rejected if it exceeds 64
- Sharpness levelCorrected to 0 to 5
L13Example05.java · Complete independent example
public class L13Example05 {
static int torchCount(int coal, int sticks) {
if (coal < 0 || sticks < 0 || coal > 64 || sticks > 64) return 0;
return Math.min(coal, sticks) * 4;
}
static int safeLevel(int level) { return Math.max(0, Math.min(5, level)); }
public static void main(String[] args) {
System.out.println(torchCount(-1, 3));
System.out.println(torchCount(0, 64));
System.out.println(safeLevel(9));
}
}Output
0
0
507 / 15
boolean method answers true or false
Methods that return boolean are suitable for answering questions. The call site reads like a sentence, so the method name should sound like a question.
- canCraftPickaxeOnly check material quantity
- trueMaterials: at least 3 diamonds and 2 wooden sticks
- falseThere is a lack of material
- Calling pointDetermine follow-up actions based on the answer
L13Example06.java · Complete independent example
public class L13Example06 {
static boolean canCraftPickaxe(int diamonds, int sticks) {
return diamonds >= 3 && sticks >= 2;
}
public static void main(String[] args) {
System.out.println(canCraftPickaxe(5, 1));
if (canCraftPickaxe(3, 2)) System.out.println("Enough material");
}
}Output
false
Enough material08 / 15
Different formulas of the same name method
Overloading allows related operations to share a method name, but the parameter lists must be different. It is suitable for "same action, different material combinations".
- Single parameter versionItem name, default quantity 1
- Dual parameter versionItem name and quantity
- Reloading rulesParameter lists must be different
- CallJava selects version by parameters
L13Example07.java · Complete independent example
public class L13Example07 {
static void giveItem(String item) { giveItem(item, 1); }
static void giveItem(String item, int count) {
System.out.println(item + " x" + count);
}
public static void main(String[] args) {
giveItem("diamond");
giveItem("Torch", 16);
}
}Output
diamond x1
Torch x1609 / 15
How to choose overloading in Java
When an overloaded method is called, Java looks at the number and type of actual parameters. If both versions are equally suitable, a "Which door should I enter" compilation error will occur.
- show(int)Integer 3 selects this version
- show(double)3.5 Select this version
- Type conversionInteger can be converted into double
- NOTECannot rely solely on return type selection
L13Example08.java · Complete independent example
public class L13Example08 {
static void show(int n) { System.out.println("Integer " + n); }
static void show(double n) { System.out.println("Decimal " + n); }
public static void main(String[] args) {
show(3);
show(3.5);
}
}Output
Integer 3
Decimal 3.510 / 15
Damage formula split calculation
Do not cram complex formulas into one line. Calculate weapons and sharpness first, then deal with critical hits, and finally deduct armor, and use Math.max to prevent damage from becoming negative.
- Actual parametersValue provided at call location
- Shape participates in calculationMethod uses a copy of the value
- returnReturn the result to the calling place
L13Example09.java · Complete independent example
public class L13Example09 {
static double damage(double base, int sharp,
boolean critical, double armor) {
if (!Double.isFinite(base) || !Double.isFinite(armor)) return 0;
base = Math.max(0, Math.min(100, base));
sharp = Math.max(0, Math.min(5, sharp));
armor = Math.max(0, Math.min(100, armor));
double raw = base + sharp * 1.5;
if (critical) raw *= 1.5;
return Math.max(0, raw - armor);
}
public static void main(String[] args) {
System.out.println(damage(7, 2, false, 5));
System.out.println(damage(7, 5, true, 0));
}
}Output
5.0
21.7511 / 15
Three types of tests reveal loopholes
Testing is not about "clicking and running a few times." Each test must have inputs, expected and actual results.
- NormalNormal hits and critical hits
- BorderLevel 0 or 5, Armor 0
- ErrorNegative numbers and non-finite decimals
- CompareDecimal testing allows minimal error
L13Example10.java · Complete independent example
public class L13Example10 {
static double damage(double base, int sharp,
boolean critical, double armor) {
if (!Double.isFinite(base) || !Double.isFinite(armor)) return 0;
base = Math.max(0, Math.min(100, base));
sharp = Math.max(0, Math.min(5, sharp));
armor = Math.max(0, Math.min(100, armor));
double raw = base + sharp * 1.5;
if (critical) raw *= 1.5;
return Math.max(0, raw - armor);
}
public static void main(String[] args) {
double result = damage(7, 2, false, 5);
System.out.println(Math.abs(result - 5.0) < 0.0001);
System.out.println(damage(-2, 9, false, -1));
System.out.println(damage(Double.NaN, 2, false, 0));
}
}Output
true
7.5
0.0| Category | Enter base, sharp, critical, armor | Expected |
|---|---|---|
| Normal | 7, 2, false, 5 | 5.0 |
| Border | 0, 0, false, 0 | 0.0 |
| Border | 7, 5, true, 0 | 21.75 |
| Correction | -2, 9, false, -1 | 7.5 |
| Error | NaN, 2, false, 0 | 0.0 |
12 / 15
Parameters and Return Value Fault Clinic
Read the method header first, it is the contract. The calling site must provide the correct number and type of arguments; every reachable path to a non-void method must return a value.
- Leak returnThere is a path but no return
- Overload conflictThe parameters are the same, only the return type is changed
- Few actual parametersQuantity does not match
- RepairCheck method contract
BadReturn.java · Intentional error example
public class BadReturn {
static int count(int n) { if (n > 0) return n; }
public static void main(String[] args) { }
}BadOverload.java · Intentional error example
public class BadOverload {
static int value(int n) { return n; }
static double value(int n) { return n; }
public static void main(String[] args) { }
}13 / 15
Challenge Damage Calculator
Create new DamageCalculator.java. The challenge method is to protect negative input, limit the sharpness to 0 to 5, and then calculate the final damage.
- Enter the contractbase and armor range from 0 to 100
- Level contractsharp corrected to 0 to 5
- Calculation rulesCustom practice injuries
- Export contractReturn a finite and non-negative value
DamageCalculator.java · Complete stand-alone example
public class DamageCalculator {
static double damage(double base, int sharp,
boolean critical, double armor) {
if (!Double.isFinite(base) || !Double.isFinite(armor)) return 0;
base = Math.max(0, Math.min(100, base));
sharp = Math.max(0, Math.min(5, sharp));
armor = Math.max(0, Math.min(100, armor));
double raw = base + sharp * 1.5;
if (critical) raw *= 1.5;
return Math.max(0, raw - armor);
}
public static void main(String[] args) {
System.out.println(damage(7, 2, false, 5));
System.out.println(damage(7, 5, true, 0));
System.out.println(damage(-2, 9, false, -1));
}
}Output
5.0
21.75
7.514 / 15
Expansion tasks and clearance review
Each file must write at least three tests, among which there must be a boundary value.
- Wooden PickaxeMaterial calculation and boundary
- Iron PickaxeCoordinate distance method
- Diamond PickaxeAdd differentiated overloading
- ReviewInterpret formal and actual parameters
Third gear operation
- Wooden pickaxe: Write torchCount(coal, sticks) to return the maximum number of torches that can be synthesized.
- Iron Pickaxe: Write distance(x1, y1, x2, y2), and return the straight-line distance between two points.
- Diamond Pickaxe: Overload three kinds of giveItem, supporting default quantity, specified quantity and specified player respectively.
| Self-evaluation | Can | Still need to practice |
|---|---|---|
| I can explain the formal and actual parameters | □ | □ |
| I can use return | □ | □ |
| I can determine whether the overload is established | □ | □ |
15 / 15
Own acceptance record
Write expectations before running, and record actual results after running. Normal cases show that the program does things; edge cases show that it knows when to stop; error cases show that it rejects unreasonable requests.
| Category | Input of your choice | Expectation and actual |
|---|---|---|
| Normal | A common value or a successful operation | Is it consistent line by line? |
| Border | Minimum value, maximum value and adjacent value | Is there one less square and one more step? |
| Error | Illegal quantity, missing object or incorrect syntax | Explicitly reject? Is the status maintained? |
- Write a bug as: triggering conditions, phenomena, causes, and minimal repairs.
- Organize a rule worth remembering and explain it in your own words. Don't just copy the definition.
- Change an example, keep a record of the test, and let the results prove your understanding.
TAKE IT WITH YOU
Take the lesson offline
The complete lesson, code, diagrams and exercises, in your preferred language.