-2

I'mm working on this program in which connects Prolog and Java GUI. And i am encountering this problem where i don't know how many solutions the prolog program is gonna pass to java and therefore i can't declare the String array with fixed-length. This is my code:

String[] options; int i;
Query qMeat = new Query(new Compound("meat", new Term[] {new Variable("X")}));
i = 0;

while(qMeat.hasMoreSolution()){
   options[i] = "" + qMeat.nextSolution().get("X");
   i++;
}

I am getting this NullPointerException, which i guess because i didn't initialize the String array to null. And i don't know how to do so. I tried java.util.Arrays.fill(options,"") But not helping =(

Please help.

Baby
  • 4,924
  • 3
  • 27
  • 50
Ye' Thura Ag
  • 123
  • 1
  • 1
  • 10
  • 2
    You're asking "How do I create an array in Java?"? (Declaring a variable which holds a reference to an array is not the same as creating an array) – user253751 Feb 21 '15 at 06:48
  • possible duplicate of [Declare array in Java?](http://stackoverflow.com/questions/1200621/declare-array-in-java) – k_g Feb 21 '15 at 06:50
  • Umm... sorry. I mean.. how can i initialize the String array with unknown length to null.. since i m getting this NullPointerException for not initializing it. Is there a way? (I'm sorry that my English is poor.) – Ye' Thura Ag Feb 21 '15 at 06:54
  • 1
    @Ye'ThuraAg There is no way. You have to use `ArrayList` like @Eran suggested below – Baby Feb 21 '15 at 06:55
  • 3
    @Ye'ThuraAg It already *is* initialized to null, that's why you get the exception. – user253751 Feb 21 '15 at 06:57

1 Answers1

4

If you don't know the required size of the array in advance, you should use an ArrayList instead.

List<String> options = new ArrayList<>();
while(qMeat.hasMoreSolution()){
   options.add("" + qMeat.nextSolution().get("X"));
}
Eran
  • 359,724
  • 45
  • 626
  • 694