将对象添加到arrayList,直到用户输入" no"

时间:2016-03-31 07:24:22

标签: java arraylist

我希望将对象添加到arrayList,直到用户输入" no"在Do While循环中,我无法使其工作,这是我到目前为止所做的:

 ArrayList<Humano> lista = new ArrayList<>();
 Scanner input = new Scanner(System.in);

    do {

        Humano h = new Humano();
        System.out.println("Name");
        h.setNombre(input.nextLine());
        System.out.println("Age");
        h.setEdad(input.nextInt());
        lista.add(h);
        System.out.println("wish to continue?");

    } while ();//user inputs "no"

类,属性,设置器和getter。

public class Humano {

private String nombre;
private int edad;


public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public int getEdad() {
    return edad;
}

public void setEdad(int edad) {
    this.edad = edad;
}
}

1 个答案:

答案 0 :(得分:1)

试试这个

import java.util.Scanner;  
import java.util.*;

public class Test
{
     public static void main(String []args){
         ArrayList lista = new ArrayList();
         Scanner input = new Scanner(System.in);
         String userInput;
         do {
            System.out.println("Name");
            lista.add(input.nextLine());
            System.out.println("SurName");
            lista.add(input.nextLine());
            System.out.println("wish to continue?");
            userInput = input.nextLine();
            System.out.println("your input is " + userInput);
        } while (!userInput.equalsIgnoreCase("NO"));
        //whether user types "no" or "No" or "nO" or "NO", it will consider all cases.
     }
}