Starter code: here
We're going to build a program that takes user input and converts it into a number. This might sound simple, but it teaches us several important programming concepts that we'll use throughout our coding journey.
When someone types something into a JOptionPane dialog, Java sees it as text (a String), even if they type numbers. Think of it like receiving a note - even if someone writes "42" on the paper, it's still just marks on paper until we interpret it as a number.
When a user enters "123" into JOptionPane:
String userInput = JOptionPane.showInputDialog("Enter a number:");
userInput contains the characters "1", "2", and "3" - not the actual number 123.
Java provides tools to convert text into numbers. The main one we'll use today is Integer.parseInt(). This method tries to convert a String into a whole number.
Consider what should happen in these cases:
Integer.parseInt("123") // Seems straightforward... Integer.parseInt("abc") // But what about this? Integer.parseInt("") // Or this? Integer.parseInt("3.14") // Or even this?
Good programs don't crash when users make mistakes. Instead, they provide helpful feedback. Before we even try to convert a String to a number, we should check:
Is there any input at all? If someone just hits "OK" without typing anything, we get an empty String (or possibly null). We should check for this first.
if (input == null || input.trim().isEmpty()) { return "Please enter a number"; }
The trim() method removes spaces from the beginning and end of the text. This means " " (just spaces) counts as empty too!
When we try to convert a String to a number, things might go wrong. Java uses something called "exceptions" to tell us about these problems. We can catch these exceptions and handle them gracefully:
try { int number = Integer.parseInt(input); // If we get here, the conversion worked! } catch (NumberFormatException e) { // If we get here, something went wrong }
Complete the process() method in the NumberProcessor class. Your method should:
1. Check if the input is null or empty
2. Try to convert the input to an integer
3. Return appropriate messages for success or failure
As you work on this, think about:
What if we wanted to handle decimal numbers too? What would need to change?
How could we make our error messages more specific? Should we tell users the difference between "abc" and "3.14" as invalid inputs?
These questions will lead us into