Reputation: 23
I can't figure out why I can't add items to the ArrayList. I have tried a couple different ways of adding items and they don't work.
class Problem {
public ArrayList<String> problems = new ArrayList<String>();
public ArrayList<String> answers = new ArrayList<String>();
private String question1 = "What is 2+2?";
private String question2 = "What is the square root of 25";
private String question3 = "What is the next number in the sequence? {2, 4, 6}";
private String question4 = "What is 8*8?";
String[] temp1 = {question1, question2, question3, question4};
for (String s : temp1)
problems.add(s);
}
I have also tried
problems.add(question1);
problems.add(question2);
problems.add(question3);
problems.add(question4);
This does not work either.
Compiler says that identifier is expected.
Upvotes: 0
Views: 161
Reputation: 673
import java.util.ArrayList;
class Problem {
public static ArrayList<String> problems = new ArrayList<String>();
public static ArrayList<String> answers = new ArrayList<String>();
private static String question1 = "What is 2+2?";
private static String question2 = "What is the square root of 25";
private static String question3 = "What is the next number in the sequence? {2, 4, 6}";
private static String question4 = "What is 8*8?";
public static void main(String [] args) {
String[] temp1 = {question1, question2, question3, question4};
for (String s : temp1)
problems.add(s);
System.out.println(""+problems);
}
}
Upvotes: 1
Reputation: 8214
Actually, you're missing a method declaration.
Try putting your code inside of a Main method:
public static void main(String[] args) {
String[] temp1 = {question1, question2, question3, question4};
for (String s : temp1)
problems.add(s);
}
}
Upvotes: 0
Reputation: 98559
Try adding import java.util.ArrayList;
to the top of your file.
You also need a main
method to run, with a signature like this:
public static void main(String[] args)
Also, you should make the string constants final
(and/or static
) if you don't plan on changing them.
Finally, temp1
is the default ("friend") visibility.
I'm assuming this is a code snippet rather than what you actually ran.
Upvotes: 7