有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用户界面可以帮助我用这个类似的代码构造,但添加了需求(正确的日期格式,必须是18岁以上)Java GUI

private void emailKeyReleased(java.awt.event.KeyEvent evt){
布尔at=false; Boolean dotcom=false

    for(int x=1; x<=email.getText().length();x++){
    if(email.getText().substring(x-1,x).equals("@") && x>3){
        at=true;
      }
    else{
         elabel.setForeground(Color.red);
         elabel.setText("Bad Email");
    }
   
    if(x>5 && email.getText().substring(x-4,x).equals(".com") && x>3){
   dotcom=true;
      }
    else{
         elabel.setForeground(Color.red);
         elabel.setText("Bad Email");
    }
    if(at==true && dotcom==true){
        elabel.setForeground(Color.blue);
        elabel.setText("Good Email");
    }
    }

我希望我的代码在(mm/dd/yy)处显示消息对话框,标签为“不正确的日期格式”或“不是18”和“18+”


共 (1) 个答案

  1. # 1 楼答案

    我创建了一个按bearth日期计算的chek years函数(使用Calendar类)。 当你运行main时,你应该输入你的停泊日期,如果你年龄大于或小于18岁,电脑会打印出来

    import java.util.Calendar;
    import java.util.Date;
    
    import javax.swing.JOptionPane;
    
    public class Main{
        public static void main(String[] args) {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, Integer.parseInt(JOptionPane.showInputDialog("Enter Year:")));
            c.set(Calendar.MONTH, Integer.parseInt(JOptionPane.showInputDialog("Enter Month:")) - 1);
            c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(JOptionPane.showInputDialog("Enter Day:")));
            JOptionPane.showMessageDialog(null, 
                    "Your date of bearth is " + 
            c.get(Calendar.DAY_OF_MONTH) + "\\" + (c.get(Calendar.MONTH) + 1) + "\\" + c.get(Calendar.YEAR));
            if (validate(c, 18)) {
                System.out.println("you\'re older then 18");
            }else {
                System.out.println("you\'re younger then 18");
            }
        }
        public static boolean validate(Calendar bearth, int yearsDiff) {
            Calendar today = Calendar.getInstance();
            if (today.get(Calendar.YEAR) - yearsDiff > bearth.get(Calendar.YEAR)) {
                return true;
            }
            if (today.get(Calendar.YEAR) - yearsDiff < bearth.get(Calendar.YEAR)) {
                return false;
            }
            if (today.get(Calendar.DAY_OF_YEAR) >= bearth.get(Calendar.DAY_OF_YEAR)) {
                return true;
            }
            return false;
        }
    }