my first NullPointerException [duplicated]

1

As you can guess the title of my question, I'm totally new to Java and programming. Without further ado, Eclipse does not let me compile for this error and tells me that it is on the line:

System.out.printf("Digite el %s numero, por favor", cadena[i]);

Here is the complete code. Thanks.

import java.util.Scanner;

public class Verificar {

    private int arreglo[];
    private boolean creciente = true;
    private String [] cadena;

    public void verificar () {
        arreglo = new int[10];
        cadena = new String[] {"Primer", "Segundo", "Tercer", "Cuarto", "Quinto", "Sexto", "Septimo", "Octavo", "Noveno", "Decimo"};
    }

    public boolean getResult() {
      for(int i = 0; i <9; i++) {   
        if(arreglo [i] < arreglo[i+1]) {
          creciente = true;
        }
        else {
          creciente = false;
        }
      }

      return creciente;
    }

    public void saveArray() {
        Scanner entrada = new Scanner(System.in);
        for(int i = 0; i < 10; i ++) {
            System.out.printf("Digite el %s numero, por favor", cadena[i]);
            arreglo[i] = entrada.nextInt();
        }
    }
}

And this code is the main:

import javax.swing.JOptionPane;

public class Output {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


    Verificar verificar = new Verificar();


    do {
        JOptionPane.showInputDialog("A continuacion se le pedira que digite 10 numeros en orden ASCENDENTE");
        verificar.saveArray();
        if(verificar.getResult()) {
            System.out.println("Los digitos fueron escritos en orden ascendente");
        }
            else {
                System.out.println("No fueron escritos en orden ascendente");
            }

    }
        while(verificar.getResult());


    }
}

Apparently the problem is in the saveArray method, but I'm not sure.

    
asked by Alexrr95 10.05.2018 в 04:29
source

1 answer

2

The problem is that you have not declared the constructor correctly, it should be public Verificar(){...} , note the correct declaration has no return type and the "v" is uppercase as is the name of the class Verificar . For that reason when you create a new instance of the class, Verificar verificar = new Verificar(); , you are calling the default constructor that has a class when you do not declare any constructor and that is why the vectors arreglo and cadena are not being initialized and gives you the null pointer error.

Your constructor should look like this:

   ...
   public Verificar () {
        arreglo = new int[10];
        cadena = new String[] {"Primer", "Segundo", "Tercer", "Cuarto", "Quinto", "Sexto", "Septimo", "Octavo", "Noveno", "Decimo"};
   }
   ...
    
answered by 10.05.2018 / 06:39
source