- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
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 Info
Table of Contents
-
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, or98F— 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 inThe starter project already has five classes under
src/main/java/lab/, each with// TODOmarkers 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:
- Bad suffix — a reading like
12.5xyzwhere the unit isn't one of the four this camp uses (km,ft,F,C). - Bad number — a reading like
abckmwhere the suffix is fine but the numeric part won't parse. - 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 number12.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
switchin 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.javanow to see the first twoTODOs waiting for you.info> If you get stuck, you can refer to the provided solution code for each task, available in the
solutionfolder. -
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.extractUnitis that first checkpoint.The natural tool here is
String#endsWith, checked against each of the four allowed suffixes. Because two of them (FandC) 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 fourendsWithchecks with&&/||into one expression rather than writing four near-identicalifblocks. Anything that doesn't match one of the four should never quietly become a zero or anull: 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 numberWith
extractUnitin place,extractNumericValuebuilds on it directly: it should callextractUnitfirst, 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
substringcall would work only if you already knew the suffix's length, which varies (F/Care one character,km/ftare two). A small regex sidesteps that:replaceFirstwith 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 forDouble.parseDouble. ## What you've builtReadingParsercan now turn"12.5km"into the unit"km"and the value12.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. -
Challenge
Step 3: Handle malformed readings and unreliable files safely
From parsing to surviving bad data
ReadingParsernow 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:SafeReadingParsercatches exactly the exceptionsReadingParserthrows, andLogFileReaderhandles 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 throwReadingParser.extractNumericValueparses the leading digits of a reading withDouble.parseDouble, which throwsNumberFormatExceptionwhen the text isn't a valid number — a subclass ofIllegalArgumentException, but distinct from the oneextractUnitthrows for an unrecognized suffix. If you writecatch (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 exceptionextractUnitfails for a different reason thanextractNumericValuedoes — an unrecognized suffix likexyzrather than an unparseable number — and it signals that withIllegalArgumentException, notNumberFormatException. Catching the wrong one here would mean a genuinely bad number silently becomes"UNKNOWN"instead ofNaN, which would make the two failure modes indistinguishable in the report.safeExtractUnitfollows 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 problemA 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.readAllLinessignals 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 athrowsclause; wrapping the call in aRuntimeExceptionto make the compiler stop complaining just hides the decision instead of making it.LogFileReadershould keep thatthrows IOExceptionvisible on the low-level read, and only catch it at the point where a real fallback makes sense. -
Challenge
Step 4: Choose conversion direction with switch
You can now parse a raw reading like
"12.5km"into a clean12.5paired 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,fromUnitandtoUnit-- exactly the kind of multi-branch decision aswitchis built for. A classic colon-styleswitchis dangerous here: forget abreakand execution slides into the next case, silently applying the wrong formula to a field reading. Java's arrow-caseswitchcloses that hole -- eachcase "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 toswitchon their concatenation, so"km" + "->" + "ft"becomes a single key like"km->ft"that aswitchcan 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. -
Challenge
Step 5: Wire the base camp converter report together
You now have every piece the camp needs:
SafeReadingParserturns a ragged string into a unit and a value without throwing,LogFileReaderturns a possibly-missing file into a list of lines, andUnitConverterturns 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.BaseCampReportties 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 --safeExtractUnitreturns"UNKNOWN"instead of throwing on a bad suffix, andsafeParseValuereturnsDouble.NaNinstead 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 makessafeParseValuethrow, becauseextractNumericValuevalidates 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 anif/elseacross 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. -
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.MainThe program reads the sample log
camp-readings.login the project folder and prints its output there: the total of the valid distance readings in kilometers. The log deliberately contains two bad lines (abckmand7.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.logThe first passes
truefor the imperial flag, so the same readings are totaled in feet. The second points at a file that doesn't exist, which triggers the0.0kmfallback you wrote inreadLogLinesOrDefault. ### Run the checks yourselfThe 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 testOr one task at a time:
bash runTest.sh task_2_1Each 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
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.