Within the while
you are changing the same instance of Agenda
(is not creating a new one, which I understood to be the intention). Moreover, if resp
for "Y"
, he will go into loop infinite, for resp
is not updated within the while
, then its value will remain "Y"
and he’ll never get out of this loop.
If resp
is not "Y"
, he doesn’t get into the while
and you add the agenda to the list (only one). Then the first thing is to fix this loop forever read a new value from resp
(to know whether or not to continue reading more data), and always create a new schedule to add to the list (instead of changing the same).
So first let’s change the class Agenda
, adding a constructor named:
public class Agenda {
private String nome;
public Agenda(String nome) {
this.nome = nome;
}
public String getNome() {
return this.nome;
}
}
I’m assuming it only makes sense to create an agenda if it has a name. So there’s no reason to have a constructor with no parameters, which creates an unnamed directory. Just create builders that make sense. I also removed the Setter because there seems to be no use for it (unless there is some rule that determines that an agenda can change its name - see more about getters and setters here).
Now let’s get our loop. One detail is that the method Scanner::next
will only read the entry until you find a space, so if the name typed is "Fulano de Tal"
, the method next()
only returns "John Doe" (and the next call next()
would read the "of"). We can resolve this by exchanging the calls of next()
for nextLine()
, which consumes the entire input until it finds a line break (in this case, the ENTER typed by the user). So would be:
Scanner scanner = new Scanner(System.in);
List<Agenda> lista = new ArrayList<Agenda>();
String resp;
do {
System.out.println("Digite o nome");
lista.add(new Agenda(scanner.nextLine()));
System.out.println("Deseja digitar outro ? ");
resp = scanner.nextLine();
} while (resp.equalsIgnoreCase("Y")); // enquanto resp for Y, continua no loop
In other words, I read a name, create an agenda with that name and add it to the list. Then I ask if the user wants to enter another name, and based on the answer, it continues or not in the do
/while
. If you want, it can also be:
while (true) {
System.out.println("Digite o nome");
lista.add(new Agenda(scanner.nextLine()));
System.out.println("Deseja digitar outro ? ");
if (! "Y".equalsIgnoreCase(scanner.nextLine()))
break; // se usuário digitou algo diferente de Y, interrompe o while
}
In the case, the break
interrupts the loop.
Finally, just print the list, making a for
by its elements and printing one by one:
for (Agenda agenda : lista) {
System.out.println(agenda.getNome());
}