2

我在 Java 上的年龄计算程序遇到了一些问题。当我预设出生年份、出生月份和出生日期值时,它工作正常,但是当我尝试让用户在文本字段中输入他们自己的出生日期然后尝试使用这些值时,我只是走到了死胡同。我尝试在 Yahoo Answers 上提问,得到的提示是“getActionCommand() 的返回值是一个字符串,而结果是一个 JLabel。你能比较它们吗?” 我不完全确定如何处理该提示。

这就是我所拥有的以及我尝试实现整个“用户输入”想法的方式。我很确定我的编码是混乱和低效的,所以请耐心等待。我会很感激任何帮助!

   //Date: April 11, 2012
   //Description: Calculates the age in terms of days depending on your birthdate.
   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;

   public class AgeCalculator extends Frame implements  ActionListener {

JButton equal;
JTextField year, month, day;
JLabel result, first, second, third;
JFrame frame;
JPanel panel;

static int totaldaysalive;
static int daysaliveyr;
static int daysalivem;
static int birthyr; 
static int birthm;
static int birthd;
static int currentyr = 2012; 


public AgeCalculator(){
    gui();
}

public void gui(){
    frame = new JFrame ("Age Calculator");
    panel = new JPanel(new GridBagLayout());
    panel.setBackground(Color.LIGHT_GRAY);
    GridBagConstraints x = new GridBagConstraints();

    equal = new JButton ("Get Result");

    x.insets = new Insets(3,0,3,0);

    first = new JLabel("Year  ");
    x.gridx = 0;
    x.gridx = 0;
    panel.add(first, x);

    year = new JTextField(10);
    x.gridx = 5;
    x.gridy = 0;
    x.gridwidth = 3;
    panel.add(year, x);

    second = new JLabel ("Month  ");
    x.gridx = 0;
    x.gridy = 1;
    panel.add(second,x);

    month = new JTextField(10);
    x.gridx = 5;
    x.gridy = 1;
    x.gridwidth = 3;
    panel.add(month,x);

    third = new JLabel ("Day      ");
    x.gridx = 0;
    x.gridy = 2;
    panel.add(third,x);

    day = new JTextField(10);
    x.gridx = 5;
    x.gridy = 2;
    x.gridwidth = 3;
    panel.add(day,x);

    x.gridx = 6;
    x.gridy = 3;
    panel.add(equal,x);

    result = new JLabel ("");
    x.gridx = 5;
    x.gridy = 5;
    panel.add(result,x);

    frame.add(panel);
    frame.setVisible(true);
    frame.setSize(350, 350);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Calc e = new Calc();

    equal.addActionListener(e);
    year.addActionListener(e);
    month.addActionListener(e);
    day.addActionListener(e);
}

class Calc implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        try {
            birthyr = Integer.parseInt(year.getText());

        } catch (NumberFormatException a) {
            result.setText("Illegal data for first field.");
            result.setForeground(Color.red);
            return;
        }

        try {

            birthm = Integer.parseInt(month.getText());

        } catch (NumberFormatException a) {

            result.setText("Illegal data for second field.");
            result.setForeground(Color.red);
            return;
        }
        try {

            birthd = Integer.parseInt(day.getText());

        } catch (NumberFormatException a) {

            result.setText("Illegal data for third field.");
            result.setForeground(Color.red);
            return;
        } 

        if (e.getActionCommand().equals (equal)){

            totaldaysalive = ageCalcYr() + ageCalcM() + birthd;
            result.setText(Integer.toString(totaldaysalive));
        }
    } 

    public int ageCalcYr(){
        for (int i = birthyr; i <= currentyr; i++){
            if ((i % 4 == 0) && (!(i % 100 == 0) || (i % 400 == 0))){
                daysaliveyr = daysaliveyr + 366;
            }
            else {
                daysaliveyr = daysaliveyr + 365;
            }
        }
        return daysaliveyr;
    }
    public int ageCalcM(){
        if (birthm == 1){
            daysalivem = daysalivem + 0;
        }
        else if (birthm == 2){
            daysalivem = daysalivem + 30;
        }
        else if (birthm == 3){
            daysalivem = daysalivem + 60;
        }
        else if (birthm == 4){
            daysalivem = daysalivem + 90;
        }
        else if (birthm == 5){
            daysalivem = daysalivem + 120;
        }
        else if (birthm == 6){
            daysalivem = daysalivem + 150;
        }
        else if (birthm == 7){
            daysalivem = daysalivem + 180;
        }
        else if (birthm == 8){
            daysalivem = daysalivem + 210;
        }
        else if (birthm == 9){
            daysalivem = daysalivem + 240;
        }
        else if (birthm == 10){
            daysalivem = daysalivem + 270;
        }
        else if (birthm == 11){
            daysalivem = daysalivem + 300;
        }
        else if (birthm == 12){
            daysalivem = daysalivem + 330;
        }
        return daysalivem;
    }
}

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AgeCalculator gui = new AgeCalculator();
    }
    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
    }
}
4

3 回答 3

3

快速愈合:

    if (e.getActionCommand ().equals ("Get Result")) { // equal)) {
        totaldaysalive = ageCalcYr () + ageCalcM () + birthd;
        result.setText (Integer.toString (totaldaysalive));
    }

如果您有时间,我可以向您发布 20 项改进。

  1. 你扩展框架,
  2. 暗示。ActionListener,但同时 AgeCalculator 有一个 JFrame(在 SwingContext 中比 Frame 更好,它是 AWT)并且有一个单独的 Actionlistener 被使用。
  3. 删除声明,最后删除覆盖方法。
    public class AgeCalculator // 扩展 Frame 实现 ActionListener 

接下来是一组可视化组件和其他属性,后面的那些是静态的 - 这禁止在同一个 JVM 上使用 2 个 AgeCalculators。这肯定不是故意的限制。

  1. 不要做一些静态的东西来关闭编译器。
  2. 如果您不确定要公开它,请将所有内容设为私有。
  3. 尽可能避免使用属性。
  4. 你什么时候会修饰标签?
    JButton 相等;
    JTextField 年月日;
    JLabel 结果,...

    ...
    静态 int 出生;
    静态 int currentyr = 2012;
  1. 在适当的地方使用简化的加法:

    daysaliveyr += 366;
    
  2. 要计算月份的天数,请将birthyr 和birthm 作为参数传递: int totaldaysalive = ageCalcYr (birthyr) + ageCalcM (birthm) +birthd; result.setText (Integer.toString (totaldaysalive));

  3. 变量 totaldaysalive 的生存时间可以减少到 2 行 - 如果有任何错误,搜索错误的范围非常小。

    public int ageCalcM (int birthm) {
        int daysalivem = 0;     
        if (birthm == 2) {
            daysalivem += 30;
        }
        else if (birthm == 3) {
            daysalivem += 60;
        }
    
  4. 在当前状态下,ageCalcM 是一个provisorium。否则你只能说daysalivem = (birthm - 1) * 30;

  5. 更短的代码:

    public int ageCalcM (int birthm) {
        if (birthm == 2) {
            return 30;
        }
        else if (birthm == 3) {
            return 60;
        }
    
  6. 然而,这种愚蠢重复的大规模操作可以用一个简单的数组来解决:

    public int ageCalcM (int birthm) {
        int[] mdays = {0, 30, 60, 90, ...};
        return mdays [birthm];
    }
    
  7. 在主方法中,您创建一个从未使用过的实例“gui”。这就是你所需要的:

    public static void main (String [] args) { new AgeCalculator (); }

  8. 桂,顺便说一句。是一个坏名字,如果你已经有一个说名字的方法。

  9. 由于从未使用过该方法,因此只需将整个内容移入 ctor 即可。
  10. 年/月/日不需要 ActionListener。
  11. 其他布局更适合。
  12. 我们需要对日历进行另一次改革,以使您的计划发挥作用。
  13. 输入不仅应检查为 int,还应检查为有效月份等。
  14. 不使用实际日期。

剩下什么?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AgeCalculator
{
    JTextField year, month, day;
    JLabel result;

    public AgeCalculator () {
        JFrame frame = new JFrame ("Age Calculator");
        JPanel panel = new JPanel (new GridBagLayout ());
        panel.setBackground (Color.LIGHT_GRAY);
        GridBagConstraints x = new GridBagConstraints ();

        JButton equal = new JButton ("Get Result");
        x.insets = new Insets (3, 0, 3, 0);

        JLabel first = new JLabel ("Year  ");
   // two times gridx = 0 here?
        x.gridx = 0;
        x.gridx = 0;
        panel.add (first, x);

        year = new JTextField (10);
        x.gridx = 5;
        x.gridy = 0;
        x.gridwidth = 3;
        panel.add (year, x);

        JLabel second = new JLabel ("Month  ");
        x.gridx = 0;
        x.gridy = 1;
        panel.add (second, x);

        month = new JTextField (10);
        x.gridx = 5;
        x.gridy = 1;
        x.gridwidth = 3;
        panel.add (month, x);

        JLabel third = new JLabel ("Day      ");
        x.gridx = 0;
        x.gridy = 2;
        panel.add (third, x);

        day = new JTextField (10);
        x.gridx = 5;
        x.gridy = 2;
        x.gridwidth = 3;
        panel.add (day, x);

        x.gridx = 6;
        x.gridy = 3;
        panel.add (equal, x);

        result = new JLabel ("");
        x.gridx = 5;
        x.gridy = 5;
        panel.add (result, x);

        frame.add (panel);
        frame.setVisible (true);
        frame.setSize (350, 350);
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

        Calc e = new Calc ();

        equal.addActionListener (e);
    }

    class Calc implements ActionListener {
        public void actionPerformed (ActionEvent e) {
            int birthyr; 
            int birthm;
            int birthd;

            try {
                birthyr = Integer.parseInt (year.getText ());
            } catch (NumberFormatException a) {
                result.setText ("Illegal data for first field.");
                result.setForeground (Color.red);
                return;
            }
            try {
                birthm = Integer.parseInt (month.getText ());
            } catch (NumberFormatException a) {
                result.setText ("Illegal data for second field.");
                result.setForeground (Color.red);
                return;
            }
            try {
                birthd = Integer.parseInt (day.getText ());
            } catch (NumberFormatException a) {
                result.setText ("Illegal data for third field.");
                result.setForeground (Color.red);
                return;
            } 
            if (e.getActionCommand ().equals ("Get Result")) { // equal)) {
                int totaldaysalive = ageCalcYr (birthyr) + ageCalcM (birthm) + birthd;
                result.setText (Integer.toString (totaldaysalive));
            }
        } 

        public int ageCalcYr (int birthyr) {
            int currentyr = 2012; 
            int daysaliveyr = 0;
            for (int i = birthyr; i <= currentyr; i++) {
                if ((i % 4 == 0) && (! (i % 100 == 0) || (i % 400 == 0))) {
                    daysaliveyr += 366;
                }
                else {
                    daysaliveyr += 365;
                }
            }
            return daysaliveyr;
        }

        public int ageCalcM (int birthm) {
            int[] mdays = {0, 30, 60, 90, 120};
            return mdays [birthm];
        }
    }

    public static void main (String [] args) {
        new AgeCalculator ();
    }
}
于 2012-04-13T01:40:02.527 回答
0

由于您使用按钮来启动计算,因此只需在该按钮上注册一个动作侦听器。在 action executed 方法中读取、解析和计算年龄(以天为单位)。

于 2012-04-13T00:49:38.333 回答
0

我想你想做equal.addMouseListener(e)。当然,您必须更改Calc以实施MouseListener. 您可能只需要实际编写该mouseClicked(MouseEvent)方法。所有其他人都是为了比你所追求的更具体的事情。

这将响应您的按钮上的单击事件。我不认为你想要任何其他听众。如果是这样,它们应该是KeyListeners或其他的东西ActionListeners

在旁注中,我很难看到,因为您的缩进已关闭,但我无法真正说出为什么您的int字段是static. 我认为这可能是不必要的。

于 2012-04-13T00:39:20.770 回答