如何为JOptionPane.showInputDialog的按钮添加命令?代码调试求助
Hey there! Let's break down what's tripping up your code—totally get not wanting to pause your practice when you're working on this at home as a high schooler 😊
First, let's look at the key issues in your current code:
1. Wrong use of JOptionPane.showInputDialog parameters
You tried passing JOptionPane.OK_CANCEL_OPTION as the second argument to showInputDialog, but that's not how this method works. The second parameter here is for the message type (like JOptionPane.PLAIN_MESSAGE), not the button options. When a user clicks Cancel or closes the input window, showInputDialog returns null—that's how we handle the cancel case.
2. Incorrect condition check
Your line if (inputAge == JOptionPane.OK_OPTION) is comparing a String (the user's input age) to an integer (JOptionPane.OK_OPTION is just the number 0). These two types can never be equal, so this condition will never trigger.
3. Missing age conversion & error handling
You declared an Integer Age variable but never converted the input string to an integer. You also don't handle cases where the user enters non-numeric text, which would cause a crash.
Here's the fixed code with explanations:
import javax.swing.JOptionPane; public class BirthYearCalculator { public static void main(String[] args) { String inputAge; Integer age; // Show input dialog with a clear title inputAge = JOptionPane.showInputDialog(null, "Enter Age To Find Your Year Of Birth", "Calculate Birth Year", JOptionPane.PLAIN_MESSAGE); // Handle if user clicks Cancel or closes the window if (inputAge == null) { System.out.println("You canceled the input!"); return; } try { // Safely convert input string to an integer age = Integer.parseInt(inputAge); // Calculate birth year using the current year int currentYear = java.time.Year.now().getValue(); int birthYear = currentYear - age; System.out.println("You Were Born around " + birthYear + "!"); } catch (NumberFormatException e) { // Catch cases where user enters non-numeric text System.out.println("Oops, that's not a valid number! Please enter your age as a whole number."); } } }
Let's go over the fixes:
- We added a proper title to the dialog and removed the incorrect
OK_CANCEL_OPTIONparameter fromshowInputDialog. - We check if
inputAgeisnullfirst to handle the Cancel case gracefully. - We use a
try-catchblock to safely convert the input string to an integer—this prevents crashes if the user enters something that's not a number. - We calculate the birth year using Java's built-in
java.time.Yearclass to get the current year accurately.
Give this a try, and let me know if you run into any other snags!
内容的提问来源于stack exchange,提问作者swazzy123

