我对异常处理相当新,我正在寻找一个特殊异常的帮助。我编写了一个GUI程序,根据用户的生日确定用户的年龄。如果用户输入的内容不是有效的生日,我想处理抛出的异常。我认为我已经正确处理了抛出的异常(NumberFormatException),但仍然显示了堆栈跟踪。有没有办法防止这种情况,或者它只是如何抛出/捕获异常的一部分? (我也很想在这个网站上发帖,所以我喜欢任何有关如何让我的帖子变得更好的反馈,谢谢!)
这是我的代码:
/*
This program was written to determine a users age based on the input of
their birthday and the current date.
Written by Randy Egan for CSC161.
Some exception handling has been implemented when entering an invalid
birthday.
*/
import java.util.Calendar;
import java.util.Scanner;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AgeCalculator extends JFrame{
public static final int WIDTH = 600;
public static final int HEIGHT = 200;
public static final int LEFT = 450;
public static final int RIGHT = 250;
//these will be used to set positioning and size for the window
private JLabel enterBDayL, userAgeL;
private JTextField enterBDayTF, userAgeTF;
private JButton clearB, calculateB;
//these will be used to set up the GUI
private Calendar cal = Calendar.getInstance();
public AgeCalculator(){
//start of GUI setup-
setTitle("Age Calculator");
enterBDayL = new JLabel("Enter your birthday in the form MM/DD/YYYY");
userAgeL = new JLabel("Your current age is");
enterBDayTF = new JTextField();
userAgeTF = new JTextField();
clearB = new JButton("Clear");
calculateB = new JButton("Calculate");
calculateB.addActionListener(new CalculateButtonHandler());
clearB.addActionListener(new ClearButtonHandler());
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,2));
pane.add(enterBDayL);
pane.add(enterBDayTF);
pane.add(userAgeL);
pane.add(userAgeTF);
pane.add(clearB);
pane.add(calculateB);
setSize(WIDTH,HEIGHT);
setLocation(LEFT,RIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class CalculateButtonHandler implements ActionListener{
//This method is where the age calculation happens
public void actionPerformed(ActionEvent e){
String rawBirthday = enterBDayTF.getText();
try{
String[] birthday = rawBirthday.split("/");
int birthMonth = Integer.parseInt(birthday[0]);
int birthDay = Integer.parseInt(birthday[1]);
int birthYear = Integer.parseInt(birthday[2]);
}
catch(NumberFormatException x){
System.err.println("Invalid Birthday Format: " + x);
enterBDayTF.setText("");
userAgeTF.setText("");
JOptionPane.showMessageDialog(null, "Please enter a birthday in the form MM/DD/YYYY");
}
String[] birthday = rawBirthday.split("/");
int birthMonth = Integer.parseInt(birthday[0]);
int birthDay = Integer.parseInt(birthday[1]);
int birthYear = Integer.parseInt(birthday[2]);
int currentDay = cal.get(Calendar.DAY_OF_MONTH);
int currentMonth= cal.get(Calendar.MONTH);
currentMonth++;
//The current month has to be incremented because in this library
//they count the months starting from 0. Without incrementing the
//month, the program works perfectly fine, except for birthday's
//in the current month, where the age is not calculated properly.
int currentYear = cal.get(Calendar.YEAR);
if(currentYear == birthYear)
userAgeTF.setText("" + 1);
//this checks to see if the user's birth year is equal to the
//current year, if it is, it returns one for the user's age
//since the user's birthday would have already passed.
if(currentMonth < birthMonth){
int age = currentYear - birthYear - 1;
userAgeTF.setText("" + age);
}
if(currentMonth > birthMonth){
int age = currentYear - birthYear;
userAgeTF.setText("" + age);
}
if(currentMonth == birthMonth && currentDay < birthDay){
int age = currentYear - birthYear - 1;
userAgeTF.setText("" + age);
}
if(currentMonth == birthMonth && currentDay >= birthDay){
int age = currentYear - birthYear;
userAgeTF.setText("" + age);
}
//this block of if statements is used to handle if the user's birthday
//has passed for the current year or not.
}
}
private class ClearButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
userAgeTF.setText("");
enterBDayTF.setText("");
}
}
public static void main(String[] args){
AgeCalculator ac = new AgeCalculator();
}
}
答案 0 :(得分:0)
问题是您正在处理异常,但您的代码仍然认为提供了有效日期。
在 AgeCalculator $ CalculateButtonHandler.actionPerformed(AgeCalculator.java:82)
将catch之后的代码移到try中。如果没有要拆分的文本,则无法拆分文本。
更正方法:
public void actionPerformed(ActionEvent e) {
String rawBirthday = enterBDayTF.getText();
try {
String[] birthday = rawBirthday.split("/");
int birthMonth = Integer.parseInt(birthday[0]);
int birthDay = Integer.parseInt(birthday[1]);
int birthYear = Integer.parseInt(birthday[2]);
int currentDay = cal.get(Calendar.DAY_OF_MONTH);
int currentMonth = cal.get(Calendar.MONTH);
currentMonth++;
//The current month has to be incremented because in this library
//they count the months starting from 0. Without incrementing the
//month, the program works perfectly fine, except for birthday's
//in the current month, where the age is not calculated properly.
int currentYear = cal.get(Calendar.YEAR);
if (currentYear == birthYear)
userAgeTF.setText("" + 1);
//this checks to see if the user's birth year is equal to the
//current year, if it is, it returns one for the user's age
//since the user's birthday would have already passed.
if (currentMonth < birthMonth) {
int age = currentYear - birthYear - 1;
userAgeTF.setText("" + age);
}
if (currentMonth > birthMonth) {
int age = currentYear - birthYear;
userAgeTF.setText("" + age);
}
if (currentMonth == birthMonth && currentDay < birthDay) {
int age = currentYear - birthYear - 1;
userAgeTF.setText("" + age);
}
if (currentMonth == birthMonth && currentDay >= birthDay) {
int age = currentYear - birthYear;
userAgeTF.setText("" + age);
}
//this block of if statements is used to handle if the user's birthday
//has passed for the current year or not.
} catch (NumberFormatException x) {
System.err.println("Invalid Birthday Format: " + x);
enterBDayTF.setText("");
userAgeTF.setText("");
JOptionPane.showMessageDialog(null, "Please enter a birthday in the form MM/DD/YYYY");
}
}
要记住的是,在尝试处理String时会抛出异常。如果无法处理字符串,因为它没有遵循所需的模式,那么您必须处理后一种逻辑,就好像您无法继续。