0

I've recently written a program to solve problem 4 of Project Euler, I managed to get the answer correct by just searching the list of palindromes for the largest palindrome product.

Now I'm trying to fine tune my program to actually search for the highest palindrome and print it out. Though I keep getting a 'null pointer exception' when trying to add the palindromes to an ArrayList, I have tried an ArrayList and also an ArrayList and both are giving the same exception.

Here is the program, the issue is with the line after:

if (this.isPalindrome(toTest)) { ...

Where I am adding to the array, I don't know what's wrong some help would be greatly appreciated! Thanks in advance.

public void PalinProduct() {
    int pos = 0;
    for (int i = 100; i < 1000; i++) {
        for (int j = 100; j < 1000; j++) {

            int x = (i * j);
            String toTest = Integer.toString(x);
            if (this.isPalindrome(toTest)) {
                palinArray2.add(toTest);
            }

        }
    }
    for (int i = 0; i < palinArray2.size(); i++) {
        int max = 0;
        if (Integer.parseInt(palinArray2.get(i)) > max) {
            pos = i;
        }
    }

    System.out.println("Largest palindrome is " + palinArray2.get(pos));
}
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • where you have initialized `palinArray2`? when you are talking about any error, please share the whole error log. – Wasi Ahmad Dec 29 '16 at 19:58
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – 001 Dec 29 '16 at 20:03
  • 1
    I've just moved the initialisation inside the PalinProduct method and it seemed to work. I don't understand why though as I initialised it within the class previously as a field and from what I've learned so far that should work fine. Would it be possible to ask to clarify why this is so? – Kristopher Barr Dec 29 '16 at 20:05
  • It looks like you're doing all this inside your PalinProduct constructor - so none of the member variables in the object will be available until after the constructor returns (unless you set them in that constructor). A simpler solution would be to move that initialization code to a new method that you call on the PalinProduct object after its constructed. – Michael Peacock Dec 29 '16 at 21:40

0 Answers0