这是我第一次使用编程语言。为什么BlueJ给我两个ArrayList的错误?我想测试我的输入,这样如果它们在arraylist中它将返回true,否则它将返回false?第2步将使用for循环。
private boolean isValidProvince(String province)
{
ArrayList<String> provinceList;
provinceList = new ArrayList<String>(10);
provinceList.add("British Columbia");
provinceList.add("Alberta");
provinceList.add("Saskatchewan");
provinceList.add("Manitoba");
provinceList.add("Ontario");
provinceList.add("Quebec");
provinceList.add("Newfoundland");
provinceList.add("Prince Edward Island");
provinceList.add("Nova Scotia");
provinceList.add("New Brunswick");
if(province.equals(province)){
return true;
}else{
return false;
}
}
答案 0 :(得分:0)
为了使用数组,你必须正确地import库(在源代码的顶部,在类之外)。此外,如果您想比较省字符串是否在列表中,您可以使用contains method,如下所示:
import java.util.ArrayList; // <- import!
public class TestA {
public static void main(String[] args) {
System.out.println(isValidProvince("Alberta"));
System.out.println(isValidProvince("Asd"));
System.out.println(isValidProvince("TEst"));
System.out.println(isValidProvince("British Columbia"));
}
private static boolean isValidProvince(String province) {
ArrayList<String> provinceList;
provinceList = new ArrayList<String>(10);
provinceList.add("British Columbia");
provinceList.add("Alberta");
provinceList.add("Saskatchewan");
provinceList.add("Manitoba");
provinceList.add("Ontario");
provinceList.add("Quebec");
provinceList.add("Newfoundland");
provinceList.add("Prince Edward Island");
provinceList.add("Nova Scotia");
provinceList.add("New Brunswick");
return provinceList.contains(province); //will return true if contains province, false otherwise (this way you avoid if block
}
}