Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

Java Base Camp: Safer Converters

A base camp outfitter collects field readings from handheld devices as plain strings such as '12.5km', '3000ft', and '98F'. The readings arrive in a log file that is sometimes missing or corrupted, and individual lines sometimes contain malformed numbers or unexpected suffixes. You are building the converter utility that camp staff run each evening: it parses each reading, validates its unit suffix, converts it to the unit the report needs, and falls back to safe defaults rather than crashing when a file or a line is bad.

Lab platform
Lab Info
Level
Beginner
Last updated
Dec 03, 2026
Duration
45m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Step 1: Explore the base camp readings pipeline

    Welcome to the base camp readings pipeline

    Every evening, base camp staff pull a log file off the handheld devices scattered around the site. Each line is a raw string like 12.5km, 3000ft, or 98F — a number glued to a unit suffix, with no guarantee the device wrote it correctly. Your job in this lab is to build the converter utility staff run against that log: it parses each reading, checks the suffix is one it understands, converts to whatever unit the nightly report needs, and keeps producing a report even when a line — or the whole file — is broken. ## The files you'll fill in

    The starter project already has five classes under src/main/java/lab/, each with // TODO markers where you'll add logic:

    • ReadingParser.java — splits a raw reading into its unit and its numeric value.
    • SafeReadingParser.java — wraps that parser so one bad line can't crash the run.
    • LogFileReader.java — reads the log file itself, with a fallback if it's missing.
    • UnitConverter.java — converts distances and temperatures between units.
    • BaseCampReport.java — wires all of the above into one printable summary.

    You'll work through them roughly in that order, running the tests for each step before moving to the next. ## Three ways input goes wrong

    Field data from handheld devices fails in three specific ways you'll need to handle deliberately rather than guess at:

    1. Bad suffix — a reading like 12.5xyz where the unit isn't one of the four this camp uses (km, ft, F, C).
    2. Bad number — a reading like abckm where the suffix is fine but the numeric part won't parse.
    3. Missing or unreadable file — the whole log doesn't exist, or the path is wrong.

    Each failure mode maps to a specific exception type at runtime, and part of what you'll practice is reading that exception in the stack trace before deciding what to catch — rather than reflexively writing catch (Exception e) everywhere. ## How the lab is structured

    • Step 2 builds the parsing core: turning "12.5km" into the unit "km" and the number 12.5, with validation.
    • Step 3 makes that parsing safe against garbled lines and a missing log file, using specific catch types and a checked-exception read path.
    • Step 4 adds the actual unit conversions, using switch in a way that can't silently fall through to the wrong case.
    • Step 5 assembles everything into buildReport, the method camp staff actually call.

    Open src/main/java/lab/ReadingParser.java now to see the first two TODOs waiting for you.

    info> If you get stuck, you can refer to the provided solution code for each task, available in the solution folder.

  2. Challenge

    Step 2: Build the measurement parsing core

    Finding the unit inside a reading

    Every raw reading is a number glued to a suffix, and every downstream piece of this lab — the safe parser, the converter, the report — depends on knowing which of the four suffixes (km, ft, F, C) a given reading uses before it can do anything else. extractUnit is that first checkpoint.

    The natural tool here is String#endsWith, checked against each of the four allowed suffixes. Because two of them (F and C) are single characters that could plausibly appear at the end of other strings too, you can't just look at the last character — you need to actually test membership in the set of four, combining the four endsWith checks with &&/|| into one expression rather than writing four near-identical if blocks. Anything that doesn't match one of the four should never quietly become a zero or a null: it should throw immediately, naming the bad reading, so a malformed suffix is caught right where it's found instead of causing a strange failure three methods downstream. ## From a validated suffix to a usable number

    With extractUnit in place, extractNumericValue builds on it directly: it should call extractUnit first, purely so that an invalid suffix fails the exact same way here as it does anywhere else that checks the unit — one rule, enforced once, reused everywhere.

    Once the unit is confirmed valid, the job is to strip it off and parse what's left. A plain substring call would work only if you already knew the suffix's length, which varies (F/C are one character, km/ft are two). A small regex sidesteps that: replaceFirst with a pattern that matches only the trailing letters — not digits, not the decimal point — removes exactly the suffix regardless of its length, leaving a numeric string ready for Double.parseDouble. ## What you've built

    ReadingParser can now turn "12.5km" into the unit "km" and the value 12.5, and it refuses anything that doesn't fit the four known suffixes or a valid number. That's the core the rest of the lab leans on — next, in Step 3, you'll wrap these two methods so a single garbled line in a real log file can't take down the whole run.

  3. Challenge

    Step 3: Handle malformed readings and unreliable files safely

    From parsing to surviving bad data

    ReadingParser now knows how to split a well-formed reading into a unit and a number — but it throws when a reading isn't well-formed, and a nightly report that crashes on the first garbled line from one device is useless. In this step you'll build the safety layer around it: SafeReadingParser catches exactly the exceptions ReadingParser throws, and LogFileReader handles the case where the log file itself can't be read. The goal isn't to catch everything — it's to catch the specific thing that specific failure produces, and to make every fallback visible rather than silently wrong. ## Matching the catch to the throw

    ReadingParser.extractNumericValue parses the leading digits of a reading with Double.parseDouble, which throws NumberFormatException when the text isn't a valid number — a subclass of IllegalArgumentException, but distinct from the one extractUnit throws for an unrecognized suffix. If you write catch (Exception e) around a call like this, you'll also catch bugs that have nothing to do with bad input, and you'll never notice until the report quietly produces wrong numbers. The fix is to look at what the method actually throws — check its declaration or run it once and read the stack trace — and catch that exact type. ## The same discipline, a different exception

    extractUnit fails for a different reason than extractNumericValue does — an unrecognized suffix like xyz rather than an unparseable number — and it signals that with IllegalArgumentException, not NumberFormatException. Catching the wrong one here would mean a genuinely bad number silently becomes "UNKNOWN" instead of NaN, which would make the two failure modes indistinguishable in the report. safeExtractUnit follows the same shape as the method you just wrote, but paired with its own exception type and its own fallback string. ## When the whole file is the problem

    A single bad line is one thing; a missing log file is another. Reading a file in Java can fail for reasons entirely outside your control — the path is wrong, the file was deleted, permissions changed overnight — and Files.readAllLines signals that with a checked exception, IOException, rather than a runtime one. Checked exceptions exist precisely so the compiler forces every caller of a risky method to either handle the failure or explicitly pass the risk along with a throws clause; wrapping the call in a RuntimeException to make the compiler stop complaining just hides the decision instead of making it. LogFileReader should keep that throws IOException visible on the low-level read, and only catch it at the point where a real fallback makes sense.

  4. Challenge

    Step 4: Choose conversion direction with switch

    You can now parse a raw reading like "12.5km" into a clean 12.5 paired with the unit "km". The next job is to turn that number into whatever unit the evening report asks for: kilometers into feet, Fahrenheit into Celsius, and so on. That means picking one of several conversion formulas based on two strings, fromUnit and toUnit -- exactly the kind of multi-branch decision a switch is built for. A classic colon-style switch is dangerous here: forget a break and execution slides into the next case, silently applying the wrong formula to a field reading. Java's arrow-case switch closes that hole -- each case "km->ft" -> ... branch runs on its own and never falls into its neighbour. A convenient trick when you're branching on two strings at once is to switch on their concatenation, so "km" + "->" + "ft" becomes a single key like "km->ft" that a switch can match directly. Distances only ever move between two units, so a same-unit case and its opposite covered the whole space. Temperature conversion has the same shape -- Fahrenheit and Celsius -- but it's worth being stricter about what happens when the units aren't one of those two. A distance suffix like "km" should never quietly produce a temperature; it should fail loudly so the mistake surfaces immediately instead of showing up as a wrong number in a report.

  5. Challenge

    Step 5: Wire the base camp converter report together

    You now have every piece the camp needs: SafeReadingParser turns a ragged string into a unit and a value without throwing, LogFileReader turns a possibly-missing file into a list of lines, and UnitConverter turns one distance unit into another without ever silently falling through to the wrong case. What's missing is the report itself -- the class that camp staff actually run each evening. BaseCampReport ties the three together: read the log, parse and total the night's readings in one unit, and print a line someone can read at a glance. Totalling a night's readings means looping over raw strings and asking two questions of each one: what unit is it in, and what is its numeric value? Both questions already have safe answers from Step 3 -- safeExtractUnit returns "UNKNOWN" instead of throwing on a bad suffix, and safeParseValue returns Double.NaN instead of throwing on a bad number. A total is only meaningful if it skips the readings those safe answers flag as broken. Check the unit first: a reading with a bad suffix makes safeParseValue throw, because extractNumericValue validates the unit before it parses. Then convert everything else into one common unit before adding it in. A total needs a unit to be expressed in, and that unit depends on who's reading the report: camp staff on site want kilometres, but a call back to headquarters might want feet. Deciding between exactly two outcomes based on one boolean is what the ternary operator is for -- it says the choice out loud in one line instead of spreading an if/else across four. Any measurement type outside distance and temperature isn't a display choice at all; it's a caller mistake, and it should fail loudly rather than quietly return a wrong label. With a totalling method and a label picker in hand, the report itself is just a sequence: load the readings, decide the unit, total them, and format the result. This is the same pattern you've been building toward since Step 1 -- reading input that might not exist, processing it defensively, and producing one clean piece of output -- now assembled end to end into the method camp staff will actually call.

  6. Challenge

    Step 6: Run the application

    Every task is done, and each one was graded the moment you completed it. What you have not done yet is watch the whole application run at once -- which is the only place the pieces you wrote separately become a single working program.

    Start the application

    Open the Terminal tab and run:

    java -cp target/classes lab.Main
    

    The program reads the sample log camp-readings.log in the project folder and prints its output there: the total of the valid distance readings in kilometers. The log deliberately contains two bad lines (abckm and 7.8xyz), so you can see them being skipped rather than crashing the run. Every behaviour it shows is code you wrote in the previous steps, so read the output against what each task asked for -- that is the whole lab, working as one program.

    Now try the other paths through your code:

    java -cp target/classes lab.Main camp-readings.log true
    java -cp target/classes lab.Main missing.log
    

    The first passes true for the imperial flag, so the same readings are totaled in feet. The second points at a file that doesn't exist, which triggers the 0.0km fallback you wrote in readLogLinesOrDefault. ### Run the checks yourself

    The lab ran each task's test for you as you went, but they are ordinary tests and you can run them whenever you like. The whole suite:

    mvn --batch-mode --quiet test
    

    Or one task at a time:

    bash runTest.sh task_2_1
    

    Each failure names the task it belongs to, so the output tells you which step to go back to rather than which line to stare at. Two things worth trying before you finish: break something on purpose and watch the matching check fail, then put it back. Knowing what a failure looks like is worth as much as knowing what a pass looks like, and it costs you nothing here.

    When you are done, everything you wrote is still in the editor tabs -- the lab is yours to keep reading.

About the author

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight