0

Im having some problems, the code below stop working when I add an int attribute in a class, the code end when ask "wish to continue"...whitout those lines the code works well. what its wrong?

public static void main(String[] args) {
     ArrayList<Humano> lista = new ArrayList<>();
     Scanner input = new Scanner(System.in);
     String userInput;
     do {
        Humano h = new Humano(); 
        System.out.println("Name");
        h.setName(input.nextLine());
        System.out.println("age");//<-----------
        h.setAge(input.nextInt());//<----------this lines causes problems
        lista.add(h);
        System.out.println("wish to continue?");
        userInput = input.nextLine();

    } while (!userInput.equalsIgnoreCase("NO"));

Class Human

public class Humano {

private String name;
private int age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}
Lazaro
  • 37
  • 5

1 Answers1

2

First answer here :)

Scanner#nextInt() method does not consume the last newline character of your input, and thus next available newline() is consumed. Best workaround for this is to add an input.nextline() after you use nextInt(), next() and nextFoo() methods.

For more answers please check this: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Community
  • 1
  • 1
MariusR
  • 21
  • 4