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);
}
}