Lazaro Lazaro - 5 months ago 20
Java Question

entering objects in an ArrayList with while loop

I cant get this code to work, while entering objects in an

ArrayList
the program ask you if you want to continue, but it skip that line and go to ask again for the name (nombre).

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Personas> persona = new ArrayList<Personas>();
char salir = 'S';
String nombre;
int edad;
while (salir == 'S') {
System.out.print("\n Nombre: ");
nombre = scan.next();
System.out.print(" edad: ");
edad = scan.nextInt();

persona.add(new Personas(edad, nombre));
System.out.print(" desea ingresar mas datos (Y/N)");

}
for (Personas datos : persona) {
System.out.println(datos);
}
}


public class Personas {
private String nombre;
private int edad;


public Personas (int edad, String nombre)
{
this.nombre = nombre;
this.edad = edad;

}
@Override
public String toString ()
{
return "\n nombre: " + nombre + "\n edad:" + edad ;
}

public String getFirst ()
{
return nombre;
}
public int getLast ()
{
return edad;
}
}

Answer

You never change your variable salir to anything else than 'S'. So your loop will run endlessly. Add a statement reading a new Value for your salir variable into your loop.

salir = (char) System.in.read();

Your should also change the initial value from salir to 'Y' and accordingly in the while check also. You're expecting an input of 'Y' or 'N' so checking for 'S' will always be false once you give your users the option to enter something.