0

I am getting the following output/error. Three numbers are being entered into the array at element zero, one and two, yet it says 'obj' is null. These numbers that are being entered should come up in the 'obj' array, but they are not. Instead '0' keeps coming up in all of those three element positions.

0 is not a prime number.
0 is not a prime number.
0 is not a prime number.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Sequence.getValue()" because "obj" is null
    at Sequences.isPrime(Sequences.java:10)
    at SequencesDriver.main(SequencesDriver.java:11)

Interface:

public interface Sequence
{

    int getValue();

}

Class:

import java.util.ArrayList;

public class PrimeSequence implements Sequence
{

    private int prime;

    ArrayList<Integer> list = new ArrayList<Integer>();
    public PrimeSequence(int n)
    {
        list.add(n);
    }

    public int getValue()
    {
        return prime;
    }

}

Class:

public class Sequences
{


    public static void isPrime(Sequence[] object)
    {
        for (Sequence obj : object)
        {
            int i, m = 0, flag = 0;
            m = obj.getValue() / 2;
            if (obj.getValue() == 0 || obj.getValue() == 1)
            {
                System.out.println(obj.getValue() + " is not a prime number.");
            }
            else
            {
                for (i = 2; i <= m; i++)
                {
                    if (obj.getValue() % i == 0)
                    {
                        System.out.println(obj.getValue() + " is not a prime number.");
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0)
                {
                    System.out.println(obj.getValue() + " is a prime number.");
                }
            }
        }
    }
}

Test/Driver:

public class SequencesDriver
{
    public static void main(String[] args)
    {
        Sequence[] obj = new Sequence[10];

        obj[0] = new PrimeSequence(3);
        obj[1] = new PrimeSequence( 5);
        obj[2] = new PrimeSequence(6);

        Sequences.isPrime(obj);

    }
}
Matt Beagle
  • 31
  • 1
  • 7
  • Your `obj` array has 10 elements. All but the first three contain null. – tgdavies Aug 14 '21 at 01:18
  • As for why `getValue()` always returns zero, please look closely at your code (`PrimeSequence` in particular) and I think you'll see why. – tgdavies Aug 14 '21 at 01:20

1 Answers1

1

You are passing in an array of 10 elements to Sequences.isPrime(obj); but only initialize 3 elements of the array.

When you loop through the array , index 3+ will be null, thus the NullPointerException.

You can reduce the size of the array to 3 or populate all elements in the array With PrimeSequence objects to eliminate NPE.

Rami Del Toro
  • 1,130
  • 9
  • 24