Java 循环测试结果为空,程序崩溃

Java 循环测试结果为空,程序崩溃,java,arrays,loops,nullpointerexception,Java,Arrays,Loops,Nullpointerexception,我一直在为一个项目筛选我的代码,但无法让这个方法按设计的那样工作。应该发生的是,系统搜索作为参数传递的数组,以查找用户输入的值。以下是编写的整个方法(我在调试中加入了一些随机文本): 我写了这句话 System.out.println(customerID[0]); 我的代码只是为了演示并确保数组已定义和初始化。另外, System.out.println(customerID[1]); 也定义了。似乎问题存在于我的循环测试中;运行 System.out.println(loop + cou

我一直在为一个项目筛选我的代码,但无法让这个方法按设计的那样工作。应该发生的是,系统搜索作为参数传递的数组,以查找用户输入的值。以下是编写的整个方法(我在调试中加入了一些随机文本):

我写了这句话

System.out.println(customerID[0]);
我的代码只是为了演示并确保数组已定义和初始化。另外,

System.out.println(customerID[1]);
也定义了。似乎问题存在于我的循环测试中;运行

System.out.println(loop + count + n)
显示它们都等于3。n在哪里设置为3

编辑 添加了@hfontanez建议的以下代码

        customerIDClone = Arrays.copyOf(customerID, count);
    for (int i = 0; i < count; i++) {
        if (customerIDClone[i] == null) {
            System.out.println("Element " + i + " is null. Creating new String.");
            customerIDClone[i] = new String();
        }
编辑2 我发现了问题。。。我有一只流浪狗;在这里:

for (n = 0; n < count; n++);
for(n=0;n

这个问题现在解决了。

Java中的数组是一个对象。创建对象数组(例如字符串数组)时,必须初始化数组和每个元素。该行:

String[] customerIDClone = new String[count];
初始化字符串对象数为“COUNT”的数组,但每个元素仍然为null。这就是为什么会出现空指针异常

在调用
customerID[count].equals(toUpdate)
之前,必须正确实例化
customerID[count]
处的(String)元素

本例中的问题是,新阵列不是原始阵列的精确副本。这一行:

customerIDClone = Arrays.copyOf(customerID, count);
创建长度为“COUNT”的新数组。如果“COUNT”大于原始元素的长度,则所有新创建的元素都用NULL填充。这解释了为什么
customerID[0]
有效,而
customerID[n]
无效。要解决此问题,可以遍历新数组,并向每个空元素添加
newstring()

更新

试试这个:

customerIDClone = Arrays.copyOf(customerID, count);
for (int i = 0; i < count; i++)
{
    if(customerIDClone[i] == null)
    {
        System.out.println("Element " + i + " is null. Creating new String.");
        customerIDClone[i] = new String();
    }
}
customerIDClone=Arrays.copyOf(customerID,count);
for(int i=0;i
BTW,
if(Arrays.asList(customerIDClone).contains(toUpdate)==true)
if(Arrays.asList(customerIDClone).contains(toUpdate))
Ah,感谢您的提示。现在更改我的代码。这是否也适用于while(Arrays.asList(customerIDClone).contains(toUpdate)==false)可以作为while(!Arrays.asList(customerIDClone).!contains(toUpdate))写入?同样更改:
while(Arrays.asList(customerIDClone).contains(toUpdate)==false)
while(!Arrays.asList(customerIDClone).contains(toUpdate))
好的,很酷。愚蠢的问题,但我似乎无法让注释中代码的四个空格格式起作用。我缺少什么?在#1键的左侧用重音字符(tilde)括起代码,但它不是由
customerIDClone=Arrays.copyOf(customerID,count)初始化的吗;
此外,我的搜索循环使用customerID而不是customerIDCloneNo…如果新数组比原始数组大,新元素将填充为NULL。请参见。在您的情况下,原始数组似乎只有一个元素;这就是为什么
customerID[0]
有效。刚刚测试了这个理论,但是customerID[1]&customerID[2]都已正确定义。此外,即使第一次循环测试通过,该值仍列为“null”。这不是一个理论。这是API上规定的事实。请转到上面我提供的一些注释的链接。
String[] customerIDClone = new String[count];
customerIDClone = Arrays.copyOf(customerID, count);
customerIDClone = Arrays.copyOf(customerID, count);
for (int i = 0; i < count; i++)
{
    if(customerIDClone[i] == null)
    {
        System.out.println("Element " + i + " is null. Creating new String.");
        customerIDClone[i] = new String();
    }
}