I am trying to register students and subjects, then add a student to a subject. All this using linked lists in Java.
So far I can add students and subjects and show the list of them but I’m not able to “link” them and show what students are taking what subject.
Code here:
package examenfinal;
/**
*
* #author USUARIO
*/
public class Alumno {
private int ID;
private String Nombre;
private int Carne;
public Alumno(int Id, String nombre, int carne) {
this.ID = Id;
this.Nombre = nombre;
this.Carne = carne;
}
public int getID() {
return ID;
}
public void setID(int Id) {
this.ID = Id;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
this.Nombre = nombre;
}
public int getCarne() {
return Carne;
}
public void setCarne(int carne) {
this.Carne = carne;
}
#Override
public String toString() {
return "Alumno{" + "ID=" + ID + ", Nombre=" + Nombre + ", Carne=" + Carne + '}';
}
}
package examenfinal;
import java.util.LinkedList;
/**
*
* #author USUARIO
*/
public class Curso {
private int Codigo;
private String Nombre;
private int Ciclo;
private int Año;
private LinkedList<Alumno> Asignar;
public Curso() {
}
public Curso(int codigo, String nombre, int ciclo, int año) {
this.Codigo = codigo;
this.Nombre = nombre;
this.Ciclo = ciclo;
this.Año = año;
}
public int getCodigo() {
return Codigo;
}
public void setCodigo(int Codigo) {
this.Codigo = Codigo;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String Nombre) {
this.Nombre = Nombre;
}
public int getCiclo() {
return Ciclo;
}
public void setCiclo(int Ciclo) {
this.Ciclo = Ciclo;
}
public int getAño() {
return Año;
}
public void setAño(int Año) {
this.Año = Año;
}
public void RegristrarAlumno(int carne, String nombre, int id){
Asignar.add(new Alumno(carne, nombre, id));
}
public LinkedList<Alumno> getAsignar() {
return Asignar;
}
}
package examenfinal;
import java.util.LinkedList;
/**
*
* #author USUARIO
*/
public class Universidad {
private LinkedList<Alumno> Inscritos;
private LinkedList<Curso> Cursos;
public Universidad()
{
Inscritos = new LinkedList<>();
Cursos = new LinkedList<>();
}
public void Crear_Curso(int cod_curso, String nombre, int ciclo, int año){
this.Cursos.add(new Curso(cod_curso, nombre, ciclo, año));
}
public void Crear_Alumno(int id, String nombre, int carne){
this.Inscritos.add(new Alumno(id, nombre, carne));
}
public void Asignar_Alumno_a_Curso(Curso curso, Alumno alumno){
curso.RegristrarAlumno(0, alumno.getNombre(), 0);
}
public LinkedList<Curso> getCursos(){
return Cursos;
}
public LinkedList<Alumno> getInscritos(){
return Inscritos;
}
}
package examenfinal;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.*;
/**
*
* #author USUARIO
*/
public final class InterfaceConsola {
private Alumno alumno1;
private Curso curso1;
private Universidad universidad1;
private Scanner in= new Scanner(System.in);
private int Opcion;
public void CrearCurso(){
System.out.println("INFORMACION DEL CURSO");
int Id;
String Nombre;
int Ciclo;
int Año;
System.out.println("CODIGO: ");
Id=(in.nextInt());
System.out.println("NOMBRE: ");
Nombre = (in.next());
System.out.println("CICLO: ");
Ciclo = (in.nextInt());
System.out.println("AÑO: ");
Año = (in.nextInt());
universidad1.Crear_Curso(Id, Nombre, Ciclo, Año);
}
public void CrearAlumno(){
System.out.println("\nINGRESE LA INFORMACION DEL ALUMNO");
System.out.println("\nID: ");
int Id;
String Nombre;
int Carne;
Id = (in.nextInt());
System.out.println("\nNOMBRE: ");
Nombre = (in.next());
System.out.println("\nNO. CARNE: ");
Carne = (in.nextInt());
universidad1.Crear_Alumno(Id, Nombre, Carne);
}
public void MostrarCursos()
{
System.out.println("CURSOS REGISTRADOS: ");
LinkedList<Curso> Cursos = universidad1.getCursos();
Iterator it =Cursos.iterator();
while (it.hasNext())
{
Curso cursoActual = (Curso) it.next();
System.out.println(cursoActual.getNombre());
}
}
public void MostrarAlumnos()
{
System.out.println("ALUMNOS REGISTRADOS: ");
LinkedList<Alumno> Alumnos = universidad1.getInscritos();
Iterator it =Alumnos.iterator();
while (it.hasNext())
{
Alumno AlumnoActual = (Alumno) it.next();
System.out.println(AlumnoActual.getNombre());
}
}
public void AsignarAlumnos(){
}
public int Menu()
{
System.out.println("UNIVERSIDAD MARIANO GALVEZ DE GUATEMALA");
System.out.println("\tMENU");
System.out.println("\n1. INGRESAR ALUMNO");
System.out.println("2. MOSTRAR ALUMNOS INSCRITOS");
System.out.println("3. CREAR CURSO");
System.out.println("4. MOSTRAR CURSOS");
System.out.println("5. ASIGNAR ALUMNOS POR CURSO");
System.out.println("6. MOSTRAR ALUMNOS POR CURSO");
System.out.println("7. SALIR");
System.out.println("SELECCIONE UNA OPCION: ");
return in.nextInt();
}
public InterfaceConsola(){
universidad1= new Universidad();
}
public void Operacion()
{
int opcion = Menu();
while (opcion!= 7)
{
if (opcion == 1)
CrearAlumno();
if (opcion == 2)
MostrarAlumnos();
if (opcion == 3)
CrearCurso();
if (opcion == 4)
MostrarCursos();
if (opcion == 5)
AsignarAlumnos();
opcion = Menu();
}
}
}
package examenfinal;
/**
*
* #author USUARIO
*/
public class ExamenFinal {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
InterfaceConsola inter1 = new InterfaceConsola();
inter1.Operacion();
}
}
YOu need to refactor Curso to accept an existing Alumno
public void RegristrarAlumno(Alumno alumno){
Asignar.add(alumno);
}
next in your InterfaceConsola#AsignarAlumnos you must do ask for student id,
retrieve the student from LinkedList.
public void AsignarAlumnos(){
System.out.println("\nINGRESE LA ID DEL ALUMNO");
int alumnoId = in.nextInt();
System.out.println("\nINGRESE LA ID DEL CURSO");
int cursoId = in.nextInt();
List<Alumno> insrictos = universidad1.getInscritos();
Alumno alumno = null;
for(Iterator<Alumno> iteratorDelInstrictos = instritos.iterator(); iteratorDelInsritos.hasNext();){
Alumno testAlumno = iteratorDelInsritos.next();
if(testAlumno.getId() == alumnoId ){
alumno = testAlumno;
break;
}
}
if(alumno == null){
System.out.println("Alumno not found);
return;
}
Curso curso = null;
for(Iterator<Curso> iteratorDelCursos = universidad.getCursos().iterator(); iteratorDelCursos.hasNext();){
Curso testCurso = iteratorDelCursos.next();
if(testCurso.getCodigo() == cursoId){
curso = testCurso;
break;
}
}
if(curso == null){
System.out.println("Curso not found);
return;
}
curso.RegristrarAlumno(alumno);
Also you need to follow Java naming guidelines (all variables are lowercase), and use generics for your iterators.
With a little less of understanding of the question and considering -
Alumno must be Student, and Curso is presumably Subject
Every Curso seem to have a list of Alumno attached to it.
private LinkedList<Alumno> Asignar
To modify/create this list, you need to
private Universidad universidad1 = new Universidad();
universidad1.getCursos().get(i).getAsignar().add(new Alumno());
where i would be the index of the Curso you're willing to update and you can replace new Alumno() with an instance of Alumno that you want to add to the list within Curso.
Related
im trying to acces the ArrayList "Lista" (with the modifications it had in the "Guardar" method) in the "verJugadores" method, is this possible? When I print the ArrayList of the "seePlayer" method I notice that it is empty, However, the one on the method "save" has an element inside of it (the attributes are assigned a value on another class), here is the code:
public class Jugador extends VentanaJugador{
private int puntuacion;
String edad1, edad;
String nombre;
String nom;
ArrayList<Jugador>lista=new ArrayList<>();
Jugador hola;
public Jugador() {
super();
}
public Jugador(int puntuacion, String nombre, String edad1, ArrayList lista) {
super();
this.hola = new Jugador();
this.puntuacion = puntuacion;
this.nombre = nombre;
this.edad1 = edad1;
this.lista = lista;
}
public int getPuntuacion() {
return puntuacion;
}
public void setPuntuacion(int puntuacion) {
this.puntuacion = 0;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getEdad() {
return edad1;
}
public void setEdad(String edad1) {
this.edad1 = edad1;
}
#Override
public String toString() {
return "Nombre: " + this.getNombre() + "\n" +
"Edad: " + this.getEdad();
}
/**
*
* #param nom
* #param edad
* #return
*/
public ArrayList guardar(String nom, String edad){
nombre = nom;
edad1=edad;
this.hola = new Jugador(puntuacion, nombre, edad1, lista);
lista.add(hola);
System.out.println("*******************");
System.out.println("Nombre: "+hola.getNombre()+"\n"+
"Edad: "+hola.getEdad()+"\n"+
"Puntuacion Inicial: "+hola.getPuntuacion());
System.out.println("*******************");
return lista;
}
public void verJugadores(){
System.out.println("*******************");
System.out.println("La lista de jugadores es:"+
"\n"+
"*******************");
if(lista.isEmpty()){
System.out.println("La lista esta vacia");
}else{
for (int i=0;i<lista.size();i++) {
System.out.println("Nombre: "+lista.get(i).getNombre());
System.out.println("Edad: "+lista.get(i).getEdad());
System.out.println("Puntuacion: "+lista.get(i).getPuntuacion());
}
}
}
}
From your guardar method, call verJugadores method, and while doing so send your ArrayList, in this case lista, as a parameter.
public ArrayList guardar(String nom, String edad){
nombre = nom;
edad1=edad;
this.hola = new Jugador(puntuacion, nombre, edad1, lista);
lista.add(hola);
System.out.println("*******************");
System.out.println("Nombre: "+hola.getNombre()+"\n"+
"Edad: "+hola.getEdad()+"\n"+
"Puntuacion Inicial: "+hola.getPuntuacion());
System.out.println("*******************");
verJugadores(lista); // calling the verJugadores method.
return lista;
Then, make changes in your verJugadores accordingly.
public void verJugadores(ArrayList<Jugador> lista){ // here parameter added..
System.out.println("*******************");
System.out.println("La lista de jugadores es:"+
"\n"+
"*******************");
if(lista.isEmpty()){
System.out.println("La lista esta vacia");
}else{
for (int i=0;i<lista.size();i++) {
System.out.println("Nombre: "+lista.get(i).getNombre());
System.out.println("Edad: "+lista.get(i).getEdad());
System.out.println("Puntuacion: "+lista.get(i).getPuntuacion());
}
Since arraylist is a non-primitive data type, the parameter in the verJugadores method will refer to the same lista.
I hope I was able to answer your question..
Neodatis create a new "Pais" when there is an equal one.
I'm working with Neodatis on a GUI. I have a database that contains "Jugadores" and "Pais." The "Jugadores" have an attribute of "Pais". When I want to add a new "Jugadores" to the database with one of the existing "Pais", recreate it in the database, since the query does not return that there is one with the same name.
GUI code:
gestionLiga gestionLiga = new gestionLiga();
gestionLiga.altaJugador(txtNombre.getText(), txtDeporte.getText(), txtCiudad.getText(), Integer.parseInt(txtEdad.getText()), gestionLiga.sacarPais(txtPais.getText()));
gestionLiga.sacarPais code:
public Pais sacarPais(String pais)
{
odb = ODBFactory.open("EQUIPOS.test");
IQuery query = new CriteriaQuery(Pais.class, Where.equal("nombre",pais));
Objects <Pais> listado = odb.getObjects(query);
if(listado.size() == 0)
{
int contador;
IQuery query2 = new CriteriaQuery(Pais.class);
Objects <Pais> listado2 = odb.getObjects(query2);
contador = listado2.size()+1;
odb.close();
return new Pais(contador, pais);
}
else
{
odb.close();
return (Pais)listado.getFirst();
}
}
gestionLiga.altaJugador code:
public void altaJugador(String nombre, String deporte, String ciudad, int edad, Pais pais)
{
odb = ODBFactory.open("EQUIPOS.test");
Jugadores jugador = new Jugadores(nombre, deporte, ciudad, edad, pais);
odb.store(jugador);
odb.close();
}
Pais class code:
class Pais
{
private int id;
private String nombre;
public Pais(){}
public Pais(int id, String nombre) {
this.id = id;
this.nombre = nombre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String toString()
{
return this.nombre;
}
}
Jugadores class code:
public class Jugadores
{
private String nombre, deporte, ciudad;
private int edad;
private Pais pais;
public Jugadores(){}
public Jugadores(String nombre, String deporte, String ciudad, int edad, Pais pais)
{
this.nombre = nombre;
this.deporte = deporte;
this.ciudad = ciudad;
this.edad = edad;
this.pais = pais;
}
public String getNombre()
{
return nombre;
}
public void setNombre(String nombre)
{
this.nombre = nombre;
}
public String getDeporte()
{
return deporte;
}
public void setDeporte(String deporte)
{
this.deporte = deporte;
}
public String getCiudad()
{
return ciudad;
}
public void setCiudad(String ciudad)
{
this.ciudad = ciudad;
}
public int getEdad()
{
return edad;
}
public void setEdad(int edad)
{
this.edad = edad;
}
public Pais getPais() {
return pais;
}
public void setPais(Pais pais) {
this.pais = pais;
}
#Override
public String toString() {
return "NOMBRE: " + nombre + " - DEPORTE: " + deporte + " - CIUDAD: " + ciudad + " - EDAD: " + edad + " - PAIS: " + pais;
}
}
If I enter two players with the same country, the query in theory should return me that there is already a Pais with that name, which should not create a new one, however, enter the IF and create a new one.
Thanks for the help!
I just don't close odb on sacarPais, then I don't open (because I can't open it twice)on altaJugador. After insert a new Jugador with Pais reference, I close the odb. It's done, a bu*****t.
I started to study java and i'm try to do a simple system to associate students and subjects, my problem is how can i associate one student to many subjects, i hope you can help me.
Main Class
package exercicios;
public class Exercicio3_Main {
public static void main(String[] args) {
//Criando Alunos
Exercicio3_Aluno aluno[] = new Exercicio3_Aluno[3];
aluno[0] = new Exercicio3_Aluno("Douglas", "Telematica", 201391);
//Criando as Disciplinas
Exercicio3_Disciplina disciplina[] = new Exercicio3_Disciplina[7];
disciplina[0] = new Exercicio3_Disciplina("POO");
aluno[0].cadastrarDisciplina(disciplina[0]);
//aluno[0].listarAluno();
}
}
Student Class
package exercicios;
import java.util.ArrayList;
public class Exercicio3_Aluno {
public String nome;
public String curso;
private int matricula;
private ArrayList<Exercicio3_Disciplina> disciplina;
public Exercicio3_Aluno(String nome, String curso, int matricula) {
super();
this.nome = nome;
this.curso = curso;
this.matricula = matricula;
}
public void listarAluno(){
System.out.println("------------- ALUNO --------------");
System.out.println("Nome: " + this.getNome());
System.out.println("Curso: " + this.getCurso());
System.out.println("Matricula: " + this.getMatricula());
System.out.println("Disciplinas: " + disciplina);
System.out.println("----------------------------------");
}
//Metodos Acessores
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public int getMatricula() {
return matricula;
}
public void setMatricula(int matricula) {
this.matricula = matricula;
}
public void cadastrarDisciplina(Exercicio3_Disciplina disciplina){
this.disciplina.add(disciplina);
}
}
Subjects Class
package exercicios;
public class Exercicio3_Disciplina {
public String nome;
private float nota1;
private float nota2;
private float nota3;
private float media;
public Exercicio3_Disciplina(String nome) {
super();
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public float getNota1() {
return nota1;
}
public void setNota1(float nota1) {
this.nota1 = nota1;
}
public float getNota2() {
return nota2;
}
public void setNota2(float nota2) {
this.nota2 = nota2;
}
public float getNota3() {
return nota3;
}
public void setNota3(float nota3) {
this.nota3 = nota3;
}
public float getMedia() {
return media;
}
public void setMedia(float media) {
this.media = media;
}
}
The output of this code is something like this:
Nome: Douglas
Curso: TLM
Matrícula: 102050
Disciplinas: Programação Orientada a Objetos
What i need is list many subjects to students, i know it's probably is very simple but i started to study this now and all of this is new for me ;D
Instead of one subject, you want multiple subjects on the student so use List<Subjects> on the student class and adjust the getters and setters as such. You can then add subjects to the list on the student.
Sample code
public static void main(String[] args) {
//Criando os Alunos
Exercicio3_Aluno aluno[] = new Exercicio3_Aluno[3];
aluno[0] = new Exercicio3_Aluno("Douglas", "TLM", 102050);
//Criando as Disciplinas
Exercicio3_Disciplina disciplina[] = new Exercicio3_Disciplina[7];
disciplina[0] = new Exercicio3_Disciplina("Programação Orientada a Objetos");
disciplina[1] = new Exercicio3_Disciplina("Sistemas Operacionais");
//Mostrando os dados do Aluno
aluno[0].cadastrarDisciplina(disciplina[0]);
aluno[0].cadastrarDisciplina(disciplina[1]);
aluno[0].listaAluno();
}
In your student method
//Lista o Aluno
public void listaAluno(){
System.out.println("--------- DADOS DO ALUNO --------");
System.out.println("Nome: " + this.nome);
System.out.println("Curso: " + this.curso);
System.out.println("Matrícula: " + this.matricula);
System.out.println("Disciplinas: ");
String disciplinasString = "";
for(Exercicio3_Disciplina disciplina : this.disciplinas)
{
disciplinasString = disciplinasString + disciplina.getNome());
}
System.out.println(disciplinasString);
System.out.println("---------------------------------");
}
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 6 years ago.
I have an issue with my program.
The error is "java.util.NoSuchElementException: No line found". I'm search a solution on stack overflow and google but i haven't find a solution.
My source code is :
FormInscreption.java
package ihm;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class FormInscription {
private String nom;
private String prenom;
private Date date_de_naissance;
private String numero_etudiant;
private String adresse;
private String courriel ;
private int numero_passport;
private int numero_permis;
private String role;
private Scanner test2 = new Scanner(System.in);
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDate_de_naissance() {
return date_de_naissance;
}
public void setDate_de_naissance(Date date_de_naissance) {
this.date_de_naissance = date_de_naissance;
}
public String getNumero_etudiant() {
return numero_etudiant;
}
public void setNumero_etudiant(String numero_etudiant) {
this.numero_etudiant = numero_etudiant;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getCourriel() {
return courriel;
}
public void setCourriel(String courriel) {
this.courriel = courriel;
}
public int getNumero_passport() {
return numero_passport;
}
public void setNumero_passport(int numero_passport) {
this.numero_passport = numero_passport;
}
public int isNumero_Permis() {
return numero_permis;
}
public void setNumero_Permis(int numero_permis) {
this.numero_permis = numero_permis;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public void readDate() throws Exception{
String dateFormat = "dd/MM/yyyy";
setDate_de_naissance(new SimpleDateFormat(dateFormat).parse(test2.nextLine()));
test2.close();
}
public FormInscription() {
try {
System.out.println("Entrer le nom :");
this.nom = test2.nextLine();
test2.close();
}
catch(Exception e){
System.out.println("erreur : "+e);
}
}
}
Menu.java
package ihm;
import java.util.Scanner;
public class Menu {
private int choix;
private Scanner sc = new Scanner(System.in);
public Menu(){
System.out.println("==== MENU ====");
System.out.println("1. Inscription");
System.out.println("2. Consultation");
System.out.println("3.Exit");
System.out.println("==============");
System.out.println("Entrez votre choix :");
try{
choix = sc.nextInt();
sc.close();
System.in.close();
}
catch(Exception e){
System.out.println("Erreur :"+e);
}
switch(choix){
case 1 :
app.System.inscription();
break;
case 2 :
System.out.println("Choix encore indisponible...");
break;
case 3 :
System.exit(0);
break;
}
}
}
System.java
package app;
//import java.io.*;
import ihm.*;
public class System {
// Fonction inscription
public static void inscription(){
FormInscription test = new FormInscription();
}
public static void main(String[] args)
{
java.lang.System.out.println("Bienvenue sur le gestionnaire du 4L Trophy");
// On affiche le menu
Menu menu = new Menu();
}
}
Thank you for help,
You should not close the System.in. when you close the Scanner, it internally closes the System.in. Try commenting
sc.close();
in Menu.Java
for more detailed answer check this out Exception in thread "main" java.util.NoSuchElementException: No line found - Using scanner input
The code run ok, but give me a Exception that I can't controlle, This is the console message:
The person with this DNI es already exists
Exception in thread "main" com.db4o.constraints.UniqueFieldValueConstraintViolationException: class: Vehiculo field: matricula
at com.db4o.constraints.UniqueFieldValueConstraint$1.ensureSingleOccurence(UniqueFieldValueConstraint.java:66)
at com.db4o.constraints.UniqueFieldValueConstraint$1.onEvent(UniqueFieldValueConstraint.java:97)
at com.db4o.internal.events.Event4Impl.trigger(Event4Impl.java:78)
at com.db4o.internal.events.EventRegistryImpl$4.run(EventRegistryImpl.java:123)
at com.db4o.foundation.DynamicVariable.with(DynamicVariable.java:54)
at com.db4o.internal.InCallback.run(InCallback.java:24)
at com.db4o.internal.events.EventRegistryImpl.withExceptionHandlingInCallback(EventRegistryImpl.java:279)
at com.db4o.internal.events.EventRegistryImpl.commitOnStarted(EventRegistryImpl.java:121)
at com.db4o.internal.LocalTransaction.dispatchCommittingCallback(LocalTransaction.java:89)
at com.db4o.internal.LocalTransaction.commit(LocalTransaction.java:66)
at com.db4o.internal.LocalTransaction.commit(LocalTransaction.java:59)
at com.db4o.internal.LocalObjectContainer.commitTransaction(LocalObjectContainer.java:689)
at com.db4o.internal.LocalObjectContainer.close2(LocalObjectContainer.java:94)
at com.db4o.internal.ObjectContainerBase.close1(ObjectContainerBase.java:361)
at com.db4o.internal.ObjectContainerBase.close(ObjectContainerBase.java:344)
at Principal.main(Principal.java:38)
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.constraints.UniqueFieldValueConstraint;
import com.db4o.constraints.UniqueFieldValueConstraintViolationException;
import com.db4o.query.Query;
public class Principal {
public static void main(String[] args) {
EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
config.common().objectClass(Persona.class).objectField("dni").indexed(true);
config.common().add(new UniqueFieldValueConstraint(Persona.class, "dni"));
ObjectContainer bbdd = Db4oEmbedded.openFile(config, "databaserrr.db4o");
Persona p = new Persona("Pepe2", 25, "50667847L");
try{
bbdd.store(p);
bbdd.commit();
System.out.println("Se ha guardado correctamente");
Query q = bbdd.query();
q.constrain(Persona.class);
ObjectSet<Persona> res = q.execute();
}catch (UniqueFieldValueConstraintViolationException e) {
System.out.println("The person with this DNI es already exists");
}finally{
bbdd.close();
}
}
}
Persona Class
public class Persona {
//Cremos atributos
private String dni;
private String nombre = null;
private int edad;
public Persona() {
}
//Constructor
public Persona(String n, int e, String d) {
nombre = n;
edad = e;
dni = d;
}
//Getter y setters
public String getDni() {
return dni;
}
public String getNombre() {
return nombre;
}
public int getEdad() {
return edad;
}
public void setDni(String d) {
dni = d;
}
public void setNombre(String n) {
nombre = n;
}
public void setEdad(int e) {
edad = e;
}
}
I find the solution to catch the exception:
catch (UniqueFieldValueConstraintViolationException e) {
System.out.println("The person with this DNI es already exists");
bbdd.rollback();
}