5
Guys need to perform the following activity:
"Consider an application to store the following data of a person in an address book: name, address, and phone. Specify a TAD to store the data of persons and the operations necessary to enter, query and delete data of persons."
Well, I need to create a class that registers a user and performs operations like query registration and deletion, well, I’m layman in java but I was able to record the data in an Arraylist, however whenever I register a new user, the previous one is overwritten, storing only the last registered. Below is the code, divided into Main class, Person and Operations. I want to know why you are overwriting and whether the code in general is in line with the statement of the question. I thank you all!
Main class:
public class exercicio {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Pessoa usuario = new Pessoa();
Operacoes acao = new Operacoes();
int op;
do {
System.out.println("[1] Inserir");
System.out.println("[2] Consultar");
System.out.println("[3] Remover");
System.out.println("[4] Sair");
System.out.print("Opção desejada: ");
op = input.nextInt();
switch (op) {
case 1:
input.nextLine();
System.out.print("Nome: ");
usuario.setNome(input.nextLine());
System.out.print("Endereço: ");
usuario.setEndereco(input.nextLine());
System.out.print("Telefone: ");
usuario.setTelefone(input.nextLine());
acao.inserePessoa(usuario);
System.out.println(usuario);
break;
case 2:
acao.consultaPessoa();
break;
case 3:
break;
}
} while (op != 4);
}}
Classe Pessoa:
public class Pessoa {
String nome;
String endereco;
String telefone;
public Pessoa() {
}
public Pessoa(String nome, String endereco, String telefone) {
this.nome = nome;
this.endereco = endereco;
this.telefone = telefone;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
@Override
public String toString() {
return "nome=" + nome + ", endereco=" + endereco + ", telefone=" + telefone;
}}
Class Operations:
public class Operacoes extends Pessoa {
ArrayList<Pessoa> listaPessoa = new ArrayList<>();
public void inserePessoa(Object usuario) {
listaPessoa.add((Pessoa) usuario);
}
public String consultaPessoa() {
for (Pessoa c: listaPessoa) {
System.out.println(listaPessoa.get(0));
}
return "oi";
}}
why you put user as Object ?
– Isvaldo Fernandes
And how would I do that? What’s the difference?
– Dan Lucio Prada
"everything is an object", that object can only be person, so you put Person.
– Isvaldo Fernandes