我无法弄清楚为什么我无法向ArrayList添加项目。我尝试了几种不同的方式添加项目,但它们不起作用。
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);
}
我也试过
problems.add(question1);
problems.add(question2);
problems.add(question3);
problems.add(question4);
这也不起作用。
编译器说预期标识符。
答案 0 :(得分:8)
尝试将import java.util.ArrayList;
添加到文件顶部。
您还需要运行main
方法,其签名如下:
public static void main(String[] args)
另外,如果您不打算更改字符串常量final
(和/或static
),则应该使字符串常量{。
最后,temp1
是默认(“朋友”)可见性。
我假设这是一个代码片段,而不是你实际运行的代码片段。
答案 1 :(得分:1)
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);
}
}
答案 2 :(得分:0)
实际上,你错过了方法声明。
尝试将代码放在Main方法中:
public static void main(String[] args) {
String[] temp1 = {question1, question2, question3, question4};
for (String s : temp1)
problems.add(s);
}
}