Error while trying to compare date

Asked

Viewed 114 times

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 that question: Comparison between dates.

However, I believe I’m comparing it wrong, since it gives me the following mistake:

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 tried to:

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;
    }
}
  • Where the error breaks?

  • On the other issue I was well emphasized in saying to use the methods after and before, but I see that you are using compareTo.

  • When the error occurs? What action do you take?

  • @Article I edited there, I put the error + complete. Error when I click on the button that tests the dates.

2 answers

2


The error occurs because dataAtual was not initiated.

Start this variable:

Date dataAtual = new Date();

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

To check also whether the difference between the years of the dates is greater than 12, without leaving much of its code and using as a basis this answer, I’ve 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;
}

Thus, it is enough to validate the return of the method, if true, the date is greater than 12 years if false, is less than 12.

See the test:

inserir a descrição da imagem aqui


As I mentioned in the other answer, it’s interesting that you use the new java8 date API, and this is very well explained all its use right here on the site.

  • before will pick up the date before, in case, to specify an interval, in case 12 years, have some option to concatenate or some other way to know ?

  • @Javinha you want to check if the date is earlier than the current one in 12 years?

  • I wanted to know if the person is at least 12 years old,.

  • @Javinha needs to be with Date? With java8 this operation is much easier.

  • I only used the util Date :( ! is very difficult ?

  • 1

    @Javinha see the edition, I did based on your code, but I think it looks pretty ugly and complex, although functional. Of course "ugly" says nothing, it is my opinion only, because with the new API is much simpler, in the answer has the explanatory link of this api.

Show 1 more comment

0

What is the value of the variable dataAtual? Java nay will save the current date in it only because of the name (even more being PT). The initial value is null and whether to confer the documentation of compareTo will read

Throws:

NullPointerException - if anotherDate is null.

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

Also it is 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.

therefore it makes no sense to compare this value with 12 - the method can return the number of seconds enter the dates, or Mili-seconds, or hours, or days, or just -1, 0 and +1...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.