0
I made a simple code to register a person in a HashMap
. Pessoa
is a class that has name and age, but is not giving to register more than one person. Every time I show her, she shows only the first one I’ve ever 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));
}
}
}
}
}
Are you using Java 7 or higher? If yes, you can use diamond operator, it makes it more elegant to instantiate a
new HashMap<>()
than anew HashMap<Integer, Pessoa>
– Jefferson Quesado
And your code is not suitable for the use of
HashMap
, would be much better with lists...– Jefferson Quesado
I know it would be better to use lists, but I have proof tomorrow and I don’t know how to use the right hashmap
– Nathan Silva
thus? Map Shows = new Hashmap<>();
– Nathan Silva