我试图在BlueJ中开始学习Java,但我很挣扎。目前我正在查看ArrayLists。以下代码正确编译:
import java.util.ArrayList;
public class TestArrayList
{
public static int colorCode;
public ArrayList<String> selection;
public TestArrayList()
{
}
private void selection()
{
selection = new ArrayList<String>();
{
selection.add("red");
selection.add("yellow");
selection.add("blue");
}
}
public void selectColor(int colorCode)
{
if (colorCode == 1)
System.out.println("You have selected " + selection.get(0) + ", the color of fire!");
if (colorCode == 2)
System.out.println("You have selected " + selection.get(1) + ", the color of electricity!");
if (colorCode == 3)
System.out.println("You have selected " + selection.get(2) + ", the color of water!");
else
System.out.println("Invalid selection");
}
}
但是当我尝试运行方法&#34;选择&#34;,并在弹出窗口中键入1,2或3时,我收到错误。所有其他值,如0,4,5,6都可以正常工作。但对于1,2和3,终端窗口显示以下错误:
java.lang.NullPointerException
at TestArrayList.selectColor(TestArrayList.java:25)
编辑器突出显示包含代码&#34; selection.get(0)&#34;的行,并返回错误&#34; java.lang.Null.Pointer异常:null&#34;。< / p>
我确信你可以从我说话的方式讲述我对Java知之甚少。我做错了很明显吗?感谢任何可以提供帮助的人。
答案 0 :(得分:3)
您的方法public TestArrayList()
{
selection();
}
未被调用。因此,您的ArrayList为null。在空引用上调用方法会导致NullPointerException。
在构造函数中调用方法。
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.setFilter(new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS).build())
.build(mActivity);
startActivityForResult(intent, REQUEST_CODE);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
}