首页 > 解决方案 > 数组索引在 for 内停止正常工作

问题描述

数组索引元素在 for cicle 外部定义良好,一旦进入,它们就会收到 Null 值。

我创建了一个名为 Auto 的类,它的构造函数有 5 个属性。我想列出一个列表,其中包含前面提到的类的 N 个(在此代码中为 3 个)对象,它们的属性是随机创建的。当我想添加一个 if 条件来停止将属性“placa”的已使用值添加到列表中时,就会出现问题。在 for 循环中,用于存储添加的所有“placa”值的​​数组对其所有值都变为 Null。

import java.util.ArrayList;
import java.lang.Math;

public class GenLista {

public void genLista() {

    int max = 3;

    ArrayList<Auto> c = new ArrayList<Auto>();
    String color[] = new String[5];
    color[0] = "Rojo"; color[1] = "Verde"; color[2] = "Azul"; color[3] = "Negro"; color[4] = "Blanco";
    String placas[] = new String[3];
    placas[0] = "JCX"; placas[1] = "HTT"; placas[2] = "CDX";

    for(int mx = 0 ; mx<max ; mx++) {

        String col = color[(int) Math.round(Math.random()*4)];
        int cap = (int) Math.round(Math.random()*10+40);
        double kilom = (Math.round(Math.random()*100000)*100.00)/100;
        String placa = placas[(int) Math.round(Math.random()*0)] + "-" + (int) Math.round(Math.random()*9);// + (int) Math.round(Math.random()*9)+ "-" + (int) Math.round(Math.random()*9) + (int) Math.round(Math.random()*9);
        double precio = (Math.round(Math.random()*100000+200000)*100.00)/100;

        Auto z = new Auto(col, cap, kilom, placa, precio);

        String plac[] = new String[max];
        System.out.println("mx = " + mx);
        plac[mx]=placa;
        System.out.println("plac" + mx + " = " + plac[mx]);
        boolean sats = false;           

        if (mx != 0) {

            for(int k=0 ; k<mx; k++) {
                System.out.println(k + "," + mx);
                System.out.println("lista plac" + k + " = " + plac[k]);

            }
        }
        else if( mx == 0) {
            sats = true;
        }

        if(sats) {
            c.add(z);
        }

        //System.out.println(z.getPlaca());
        //System.out.println(c);
    }
}
}

出口是:

mx = 0
plac0 = JCX-3
mx = 1
plac1 = JCX-5
0,1
lista plac0 = null
mx = 2
plac2 = JCX-8
0,2
lista plac0 = null
1,2
lista plac1 = null
mx = 3

在出口处,您可以注意到数组 plac 的 0 索引中应该有 JCX-5,如打印“plac0 = JCV-5”所示,但在 for 中,结果为 Null,如在打印“lista plac0 = null”。

标签: javaarrayslist

解决方案


索引超出范围

数组是零索引的。这意味着引用数组中每个插槽的数字从零开始计数。因此,一个大小为 3 的数组arr将包含三个插槽,由数字arr[0]arr[1]和引用arr[2]

当条件为真时,您编写的 for 循环将运行代码主体。在这里,您有一个大小为 3 的数组。max条件使得mx迭代到任何小于或包括3 的数字。因此,在最后一次迭代中,mx为 3,您尝试获取第 3 个插槽,但如上所述,第 2 个插槽是您可以抓住的最高位置。只需将条件更改为:

for(int mx = 0; mx < max ; mx++) {
    // ...
}

空问题

在循环的每个外部迭代中,您声明一个全新的数组:

String plac[] = new String[max];

这意味着plac您在其他迭代中修改的所有先前元素都将丢失。因此,要解决此问题,只需将此代码移出循环即可。


推荐阅读