This project demonstrates the propagation and handling of NumberFormatException. It simulates an RPG game where a player's string input is converted into a numeric gold amount. The utility method delegates the error handling to the caller, ensuring that invalid text input does not crash the game.
- Task: Create
convertToGoldAmount(String playerInput)method. - Mechanism: Declare
throws NumberFormatExceptionin the method signature. - Implementation: Use
Integer.parseInt()to convert player input. - Goal: Catch the exception in the
mainmethod and display a user-friendly error message in English.
- Java 8+
The conversion logic is encapsulated in a dedicated method. If Integer.parseInt() encounters a string that cannot be parsed into an integer (e.g., "invalid_amount"), it throws a NumberFormatException. This exception propagates to the main method, where the try-catch block intercepts it and prints a descriptive error message.
Player Error: Invalid value entered. Number conversion error.
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
try {
int gold = convertToGoldAmount("invalid_amount");
System.out.println("Gold amount: " + gold);
} catch (NumberFormatException e) {
System.out.println("Player Error: Invalid value entered. Number conversion error.");
}
}
public static int convertToGoldAmount(String playerInput) throws NumberFormatException {
return Integer.parseInt(playerInput);
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT