In my code below, I'm trying to call the RandomStringChooser constructor in the RandomLetterChooser subclass constructor.
In order to pass an array as the parameter, I call the getSingleLetters method in super(). However, I'm getting the following error:
"cannot reference this before superclass constructor has been called"
with an arrow pointing at the "g" in getSingleLetters (3rd line of subclass).
Why is this and how should I fix?
FYI: This is my attempted solution to the 1.b. of the AP Computer Science 2016 FRQ (https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap16_frq_computer_science_a.pdf). Their solution (https://secure-media.collegeboard.org/digitalServices/pdf/ap/apcentral/ap16_compsci_a_q1.pdf) involves an ArrayList (or List, I'm not completely sure about the difference between these two), which I realize is much cleaner, but still calls the getSingleLetters method in the same way as I have done below (and thus should have the same error when run).
class RandomStringChooser {
private int length;
private int count = 0;
private String word;
private String newArray[];
RandomStringChooser(String[] array) {
length = array.length;
newArray = new String[length];
for(int i = 0; i < length; i++) {
newArray[i] = array[i];
}
}
String getNext() {
if(count == length) return "NONE";
word = "";
while(word.equals("")) {
int index = (int) (Math.random() * length);
word = newArray[index];
newArray[index] = "";
}
count++;
return word;
}
}
class RandomLetterChooser extends RandomStringChooser{
RandomLetterChooser(String str) {
super(getSingleLetters(str)); //here's the problem
}
String[] getSingleLetters(String str) {
String[] letterArray = new String[str.length()];
for(int i = 0; i < str.length(); i++) {
letterArray[i] = str.substring(i, i+1);
}
return letterArray;
}
}
And here's where I run the program, in case it helps:
public class AP2 {
public static void main(String[] args) {
String ball = "basketball";
RandomLetterChooser s = new RandomLetterChooser(ball);
for(int i = 0; i < 12; i++) {
System.out.print(s.getNext() + " ");
}
}
}