Error trying to compare date

2

I'm trying to create a validation, to know if the user is at least 12 years old.

I tried to base myself on this question: Comparison between dates .

However, I think I'm comparing it wrongly, since it gives me the following error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Date.getMillisOf(Date.java:958)
at java.util.Date.compareTo(Date.java:978)
at validacoes.IdadeMaior.testeData(IdadeMaior.java:55)
at validacoes.IdadeMaior.lambda$botao$0(IdadeMaior.java:47)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) 

What should I do?

What I've tried:

import com.toedter.calendar.JDateChooser;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class IdadeMaior extends JFrame {

    JLabel dataNascLabel = new JLabel("Data nascimento: ");
    JDateChooser dataNasc = new JDateChooser();
    JButton botao = new JButton("Calcular");

    public static void main(String[] args) {
        IdadeMaior idade = new IdadeMaior();
        idade.setVisible(true);
    }

    public IdadeMaior() {

        JPanel painel = new JPanel();
        painel.setLayout(new FlowLayout());

        painel.add(dataNascLabel);
        painel.add(dataNasc);
        dataNasc.setPreferredSize(new Dimension(105, 23));

        painel.add(botao);
        botao.setPreferredSize(new Dimension(90, 22));
        botao();
        add(painel);

        setSize(500, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void botao() {
        botao.addActionListener((ActionEvent e) -> {
            testeData();
        });
    }

    Date dataAtual;

    private boolean testeData() {
        //data não pode ser menor que 12
        if (dataNasc.getDate().compareTo(dataAtual) <= 12) {
            //if (dataNasc.getDate().before(dataAtual)) {

            System.out.println("Data digitada: " + dataNasc.getDate());

            JOptionPane.showMessageDialog(null, "Erro!");
            dataNasc.requestFocus();
            return false;
        }
        return true;
    }
}
    
asked by anonymous 09.09.2017 / 21:19

2 answers

2

The error occurs because dataAtual was not started.

Start this variable:

Date dataAtual = new Date();

Another thing is to always check if the value retrieved from the component is not null, and use before to compare if one date is earlier than another.

To also check if the difference between the years of the dates is greater than 12, without leaving much of your code and using as a basis < strong> this answer , I made some modifications to your method:

private boolean testeData() {
    //data não pode ser menor que 12

    boolean dataValida = false;

    Date dataNascimento =  dataNasc.getDate();

    if (dataNascimento != null && dataNascimento.before(dataAtual)) {

        Calendar cDataAtual = new GregorianCalendar();
        Calendar cDataNasc = new GregorianCalendar();

        cDataAtual.setTime(dataAtual);
        cDataNasc.setTime(dataNascimento);

        int diferenca = cDataAtual.get(Calendar.YEAR) - cDataNasc.get(Calendar.YEAR);

        if (cDataAtual.get(Calendar.MONTH) < cDataNasc.get(Calendar.MONTH) || cDataAtual.get(Calendar.MONTH) == cDataNasc.get(Calendar.MONTH) && cDataAtual.get(Calendar.DAY_OF_MONTH) < cDataNasc.get(Calendar.DAY_OF_MONTH)) {
            diferenca--;
                }
        dataValida = diferenca >= 12 ? true : false;
    } 

    return dataValida;
}

In this way, just validate the method return, if true , the date is greater than 12 years, if false , is less than 12.

See the test:

AsImentionedintheotheranswer,it'sinterestingthatyouuse the new java8 date API , and this is very well explained all its use right here on the site.

    
09.09.2017 / 21:43
0

What is the value of dataAtual ? Java no will save the current date on it just because of the name (still more being PT). The starting value is null and is checked at documentation of compareTo will read

  

Throws:

     

NullPointerException - if anotherDate is null .

dataAtual = ... , maybe dataAtual = new Date() is missing.

It is also advisable to check the meaning of the value returned by this method:

  

the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

So it does not make sense to compare this value with 12 - method can return the number of seconds between dates, or milli-seconds, or hours, or days, or just -1, 0 and +1 ...

    
09.09.2017 / 21:39