← Java tutorials

LESSON 04 / 40 · FREE TUTORIAL

The Miner's Calculator

Turn "is it enough" and "is it worth it" into verifiable calculations?

90–110 minutesJava 11+Beginner

WHAT YOU WILL MAKE

Make miner income calculator

With seven pieces of coal and ten wooden sticks, how many torches can be synthesized? How many sets can 150 cobblestones hold? How to deduct the cost from the income of a mining trip? These questions do not require the computer to guess the answers, only the rules need to be written as expressions. In this lesson, we will distinguish between arithmetic, comparison and logic, and arrange boundary tests for the results.

Before you start: It is recommended to complete Lessons 1–3 first

01 / 11

First clarify the problem, then choose the operator

Calculating resources before entering the mine is more confident than guessing how long you can last in the dark.
Calculating resources before entering the mine is more confident than guessing how long you can last in the dark.

To calculate a quantity, arithmetic operations are usually required; to ask "whether it is enough" requires comparison; when multiple requirements appear at the same time, logic must be used to connect them. The results obtained by the three operations are different. Don't confuse "how much" and "whether it is enough" into the same thing.

  • How many torches? Get an integer.
  • Is the profit at least 50? Gets true or false.
  • Profits reached the target and diamonds were dug? Still get true or false.

02 / 11

Five computing tools: + - * / %

By breaking down each calculation step, complex results will have traceable sources.
By breaking down each calculation step, complex results will have traceable sources.

Snippet: place inside main and run separately

int coal = 7, sticks = 10, blocks = 150;
System.out.println(coal + 3);
System.out.println(sticks - coal);
System.out.println(coal * 4);
System.out.println(blocks / 64);
System.out.println(blocks % 64);

Output

10
3
28
2
22

Addition records acquisition, subtraction records consumption, and multiplication processes "a few per group". For non-negative item quantities, use / to count complete sets and % to count remaining quantities. The calculation here is temporarily based on the practice rule of up to 64 items per group for one item.

03 / 11

Priority: Who is calculated first?

Commonly used operators in this lesson, from high to low
LayerOperatorReading Tips
Brackets( )First clarify the grouping
Negation!Flip true and false
Remainder of multiplication and division* / %The same layer is usually from left to right
Addition and subtraction+ -Also pay attention to string splicing
Size comparison> >= < <=get boolean
Equality comparison== !=get boolean
Logical AND&&Both are satisfied
Logical OR||At least one satisfies

Snippet: place inside main and run separately

System.out.println(2 + 3 * 4);
System.out.println((2 + 3) * 4);
int total = 3 * 12 + 5;
System.out.println(total);

Output

14
20
41

04 / 11

Complete group and remainder, transport grid and box

150 = 2 × 64 + 22
  1. Group 164
  2. Group 264
  3. Remaining22

Snippet: place inside main and run separately

int blocks = 150;
int fullStacks = blocks / 64;
int leftover = blocks % 64;
System.out.println(fullStacks + " Group, remainder " + leftover);
int slotsNeeded = (int) Math.ceil(65 / 64.0);
System.out.println("65 The number of grids required for each item=" + slotsNeeded);

Output

2 Group, remainder 22
65 The number of grids required for each item=2

The second result is the number of inventory slots, not the number of boxes. Here it is set that 64 items of an item are placed in each grid; boxes will have multiple grids, and to calculate the number of boxes, one must also know the number of grids in each box. Let’s talk about the units first before the calculation makes sense.

05 / 11

Comparison: Use one question to get true and false

Six comparisons, check item by item
Operatordiamonds = 4 hoursResult
>4 > 2true
>=4 >= 4true
<4 < 10true
<=4 <= 3false
==4 == 4true
!=4 != 0true

Snippet: place inside main and run separately

int diamonds = 4;
System.out.println(diamonds > 2);
System.out.println(diamonds >= 4);
System.out.println(diamonds < 10);
System.out.println(diamonds <= 3);
System.out.println(diamonds == 4);
System.out.println(diamonds != 0);

Output

true
true
true
false
true
true

06 / 11

Logic: Connect the two answers

AND, OR and NOT combine or reverse conditions. The redstone gates in the illustration help us remember what each operator does.
AND, OR and NOT combine or reverse conditions. The redstone gates in the illustration help us remember what each operator does.
First look at the two inputs, then look at the results
ABA && BA || B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

!true is false; !false is true.

Snippet: place inside main and run separately

int torches = 24;
boolean hasPickaxe = true;
boolean ready = torches >= 20 && hasPickaxe;
boolean canStay = false || true;
System.out.println(ready);
System.out.println(canStay);
System.out.println(!ready);

Output

true
true
false

&& requires both left and right sides to be satisfied; || only needs to be satisfied on at least one side. They also short-circuit: when the left-hand side of && is false and the left-hand side of || is true, the right-hand side does not have to be evaluated. Lesson 5 will use this to avoid calling methods on null.

07 / 11

Math: Give common calculations a good name

Four commonly used tools
MethodExampleResult
Math.minMath.min(7, 10)7
Math.maxMath.max(18, 23)23
Math.roundMath.round(12.6)13(long)
Math.ceilMath.ceil(129 / 64.0)3.0(double)

Snippet: place inside main and run separately

int batches = Math.min(7, 10);
int torches = batches * 4;
long distance = Math.round(12.6);
int slots = (int) Math.ceil(129 / 64.0);
System.out.println(torches);
System.out.println(distance);
System.out.println(slots);

Output

28
13
3

The torch formula will be limited by a small number of materials, so first take the smaller value of coal and sticks, and then multiply by 4. round is used for the nearest integer in this case; ceil is used for capacity calculations where no fractions can be missed.

08 / 11

Errors cannot be solved just by changing the symbols

To check the calculator, you need to distinguish between grammatical errors, operational errors and rule errors.
To check the calculator, you need to distinguish between grammatical errors, operational errors and rule errors.

Three situations, three different clues

  • Write diamonds == 3 as diamonds = 3: query becomes assignment, intent changes.
  • Integer division by 0: ArithmeticException will be thrown at runtime.
  • Treat negative numbers as the number of ores: the grammar may be legal, but it does not comply with the rules of this work.

Snippet: place inside main and run separately

int players = 0;
boolean canDivide = players != 0;
System.out.println(canDivide);

Output

false

Capacity calculation measures at least 0, 63, 64, 65: the required number of cells should be 0, 1, 1, 2. Don't just test the 150 you're already familiar with.

09 / 11

First design the rules for mining revenue

The same record must record income and consumption at the same time, and cannot just focus on the diamonds dug.
The same record must record income and consumption at the same time, and cannot just focus on the diamonds dug.
Four Steps to Profit Calculator
  1. Initial dataOre quantity
    Torches and food
  2. PricingRevenue minus cost
  3. JudgmentProfit at least 50
    And there are diamonds
  4. ReportData, profit
    With judgment result

Set the practice unit prices of coal, iron, gold, redstone, and diamond to 1, 3, 5, 2, and 12 respectively. Torches cost 1 each, and food costs 2 each. The same “practice points” are used for unit prices to avoid mixing units.

  • Income: multiply the quantity of each ore by the unit price, and then add them up.
  • Cost: Number of torches plus twice the amount of food.
  • Profit: income minus costs; losses are allowed.
  • Invalid data: If the number is negative, a prompt will be given first.

10 / 11

Complete work: Check first, then calculate

Complete program · MinerCalculator.java

public class MinerCalculator {
    public static void main(String[] args) {
        int coal = 20, iron = 8, gold = 3;
        int redstone = 12, diamonds = 2;
        int torchesUsed = 16, foodUsed = 4;
        boolean valid = coal >= 0 && iron >= 0 && gold >= 0
            && redstone >= 0 && diamonds >= 0
            && torchesUsed >= 0 && foodUsed >= 0;
        // First borrow a conditional goalkeeper; 7 The class will unfold it.
        if (!valid) {
            System.out.println("The quantity must be a non-negative integer");
            return;
        }
        int income = coal + iron * 3 + gold * 5
            + redstone * 2 + diamonds * 12;
        int cost = torchesUsed + foodUsed * 2;
        int profit = income - cost;
        boolean richTrip = profit >= 50 && diamonds > 0;
        System.out.println("Income=" + income + ", Cost=" + cost);
        System.out.println("Profit=" + profit);
        System.out.println("Harvest=" + richTrip);
    }
}

Output

Income=107, Cost=24
Profit=83
Harvest=true

11 / 11

Let boundary values check your ideas

The ability map of the fourth lesson
  1. Count quantity+ - * / %
  2. mark boundaryBrackets and units
  3. Ask whether it is true or falseComparison operation
  4. With conditions&& || !
  5. CheckNormal and borderline
  • Basics: 389 cobblestones, a complete set of 6, and a remainder of 5; at least 7 squares are required when each square has 64.
  • Advanced: Torches are at least 20 and have a mine pickaxe, and there is at least one type of food or bed. Write the judgment in parentheses.
  • Creation: Design a discount formula and use Math.max(1, calculated price) to set your own minimum price rule.

Test the complete work

Set all ores to 0, retain consumption: profit should be -24, harvest should be false. Set coal to -1: only output quantity hints. Adjust the cost to make the profit exactly 50, and then observe the difference between diamonds being 0 and greater than 0.

Technical reference: Expressions in Chapter 15 of the Math API and Language Specification of Java SE 11. For official documents, see docs.oracle.com.

TAKE IT WITH YOU

Take the lesson offline

The complete lesson, code, diagrams and exercises, in your preferred language.