I made a simple code to register a person with a HashMap
. Pessoa
is a class that has name and age, but is not giving to register more than one person. Whenever I'm going to show it, it shows only the first one I registered.
My code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int op;
String nome;
int ide;
int j = 0;
Scanner sc = new Scanner(System.in);
Map<Integer,Pessoa>Mostra = new HashMap<Integer,Pessoa>();
while(true){
System.out.println("1-Cadastrar");
System.out.println("2-Mostrar todas");
op = sc.nextInt();
if(op == 1) {
if(Mostra.isEmpty()) {
System.out.println("Nome");
nome = sc.next();
System.out.println("idade");
ide = sc.nextInt();
Pessoa p = new Pessoa(nome,ide);
Mostra.put(1,p);
}else {
System.out.println("Nome");
nome = sc.next();
System.out.println("idade");
ide = sc.nextInt();
Pessoa p = new Pessoa(nome,ide);
for(int i = 0; i < Mostra.size(); i++) {
j++;
}
Mostra.put(j,p);
}
}else if(op == 2) {
for(int i = 0; i < Mostra.size(); i++) {
System.out.println(Mostra.get(i));
}
}
}
}
}