Array index elements are well defined outside a for cicle, once in, they recieve the Null value.
I made a class called Auto which has 5 attributes on its consutructor. I want to make a list in which I will have N (3 in this code) objects of the previously mentioned class with their attributes created randomly. The issue arises when I want to add an if condition to stop objects with an already used value for the attribute "placa" being added to the list. When in the for cycle the array made to store all the "placa" values added becomes Null for all its values.
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);
}
}
}
The exit is:
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
In the exit you can notice that the array plac should have JCX-5 in its 0 index, as shown in the print "plac0 = JCV-5", but when in the for, the result is Null, as one can see in the print "lista plac0 = null".