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();
}
Related
I'm trying to print some JSONObjects from a JSONArray in JAVA using the MVC pattern and the json.simple library, but when I run it the program just print the last JSONObject.
This is my Main class:
package Main;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import Controlador.Controlador;
import Vista.Vista;
import Modelo.Modelo;
public class Main {
private static String ID;
public static void main(String[] args) throws IOException, InterruptedException {
Modelo modelo = llenarDatosModelo();
Vista vista = new Vista();
//se crea un objeto controlador y se le pasa el modelo y la vista
Controlador controlador = new Controlador(modelo, vista);
// se muestra los datos
controlador.actualizarVista();
}
//método estático que retorna el autor con sus datos
private static Modelo llenarDatosModelo() {
JSONParser jsonParser = new JSONParser ();
try(FileReader reader = new FileReader ("datos.json")) {
JSONObject documento = (JSONObject) jsonParser.parse(reader);
JSONObject resultados = (JSONObject)documento.get("search-results");
JSONArray Entrys = (JSONArray) resultados.get("entry");
for(Object Entry: Entrys) {
mostrarInformacionEntry ((JSONObject) Entry);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ParseException e) {
e.printStackTrace();
}
Modelo autor = new Modelo();
autor.setID(ID);
return autor;
}
private static void mostrarInformacionEntry(JSONObject entry) {
ID = (String) entry.get("dc:identifier");
}
This is my model:
package Modelo;
public class Modelo {
private String ID;
private String url;
private String eid;
private String document_count;
private String cited_by_count;
private String citation_count;
private String affiliation;
private String give_name;
private String classification;
private String publication_start;
private String publication_end;
public Modelo() {
}
public String getID() {
return ID;
}
public void setID(String string) {
this.ID = string;
}
public String geturl() {
return url;
}
public void seturl(String url) {
this.url = url;
}
public String geteid() {
return eid;
}
public void seteid(String eid) {
this.eid = eid;
}
public String getdocument_count() {
return document_count;
}
public void setdocument_count(String document_count) {
this.document_count = document_count;
}
public String getcited_by_count() {
return cited_by_count;
}
public void setcited_by_count(String cited_by_count) {
this.cited_by_count = cited_by_count;
}
public String getcitation_count() {
return citation_count;
}
public void setcitation_count(String citation_count) {
this.citation_count = citation_count;
}
public String getaffiliation() {
return affiliation;
}
public void setaffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getgive_name() {
return give_name;
}
public void setgive_name(String give_name) {
this.give_name = give_name;
}
public String getclassification() {
return classification;
}
public void setclassification(String classification) {
this.classification = classification;
}
public String getpublication_start() {
return publication_start;
}
public void setpublication_start(String publication_start) {
this.publication_start = publication_start;
}
public String getpublication_end() {
return publication_end;
}
public void setpublication_end(String publication_end) {
this.publication_end = publication_end;
}
}
This is my View:
package Vista;
public class Vista {
public void imprimirDatos(String string,String url, String eid, String document_count, String cited_by_count, String citation_count, String affiliation, String give_name, String classification, String publication_start, String publication_end) {
System.out.println("\n****AUTOR****");
System.out.println("ID: "+string);
System.out.println("url: "+url);
System.out.println("eid: "+eid);
System.out.println("document_count: "+document_count);
System.out.println("cited_by_count: "+cited_by_count);
System.out.println("citation_count: "+citation_count);
System.out.println("affiliation: "+affiliation);
System.out.println("give_name: "+give_name);
System.out.println("classification: "+classification);
System.out.println("publication_start: "+publication_start);
System.out.println("publication_end: "+publication_end);
}
}
And this is my controller:
package Controlador;
import Modelo.Modelo;
import Vista.Vista;
public class Controlador {
//objetos vista y modelo
private Vista vista;
private Modelo modelo;
//constructor para inicializar el modelo y la vista
public Controlador(Modelo modelo, Vista vista) {
this.modelo = modelo;
this.vista = vista;
}
//getters y setters para el modelo
public String getID() {
return modelo.getID();
}
public void setID(String ID) {
this.modelo.setID(ID);
}
public String geturl() {
return modelo.geturl();
}
public void seturl(String url) {
this.modelo.seturl(url);
}
public String geteid() {
return modelo.geteid();
}
public void seteid(String eid) {
this.modelo.seteid(eid);
}
public String getdocument_count() {
return modelo.getdocument_count();
}
public void setdocument_count(String document_count) {
this.modelo.setdocument_count(document_count);
}
public String getcited_by_count() {
return modelo.getcited_by_count();
}
public void setcited_by_count(String cited_by_count) {
this.modelo.setcited_by_count(cited_by_count);
}
public String getcitation_count() {
return modelo.getcitation_count();
}
public void setcitation_count(String citation_count) {
this.modelo.setcitation_count(citation_count);
}
public String getaffiliation() {
return modelo.getaffiliation();
}
public void setaffiliation(String affiliation) {
this.modelo.setaffiliation(affiliation );
}
public String getgive_name() {
return modelo.getgive_name();
}
public void setgive_name(String give_name) {
this.modelo.setgive_name(give_name);
}
public String getclassification() {
return modelo.getclassification();
}
public void setclassification(String classification) {
this.modelo.setclassification(classification);
}
public String getpublication_start() {
return modelo.getpublication_start();
}
public void setpublication_start(String publication_start) {
this.modelo.setpublication_start(publication_start);
}
public String getpublication_end() {
return modelo.getpublication_end();
}
public void setpublication_end(String publication_end) {
this.modelo.setpublication_end(publication_end);
}
//pasa el modelo a la vista para presentar los datos
public void actualizarVista() {
vista.imprimirDatos(modelo.getID(),modelo.geturl(), modelo.geteid(), modelo.getdocument_count(), modelo.getcited_by_count(), modelo.getcitation_count(), modelo.getaffiliation(), modelo.getgive_name(), modelo.getclassification(), modelo.getpublication_start(), modelo.getpublication_end());
}
}
When I run it the console shows this:
****AUTOR****
ID: SCOPUS_ID:85137292444
url: null
eid: null
document_count: null
cited_by_count: null
citation_count: null
affiliation: null
The JSONArray Entrys have multiple articles, I want the program to print them all. Does anyone know what I'm doing wrong?
The JSON File is:
https://drive.google.com/file/d/1t53qiU64eJVUupDA-Ie2ZR1Xakz7npGI/view?usp=sharing
Your method mostrarInformacionEntry is reading the fields of one JSON array entry. Your problem is, that this method isn't creating a new model per entry. Instead it assigns the read value dc:identifier to the class variable ID. This is done for all entries in the array. An entry overwrites the saved ID of the previous entry. At the end you create a model with the ID of the last loaded entry. But you should create a model for each entry.
You need a custom entry class/POJO:
public class ModeloEntry {
private String ID;
private String url;
private String eid;
private String document_count;
private String cited_by_count;
private String citation_count;
private String affiliation;
private String give_name;
private String classification;
private String publication_start;
private String publication_end;
public ModeloEntry() {
}
public String getID() {
return ID;
}
public void setID(String string) {
this.ID = string;
}
public String geturl() {
return url;
}
public void seturl(String url) {
this.url = url;
}
public String geteid() {
return eid;
}
public void seteid(String eid) {
this.eid = eid;
}
public String getdocument_count() {
return document_count;
}
public void setdocument_count(String document_count) {
this.document_count = document_count;
}
public String getcited_by_count() {
return cited_by_count;
}
public void setcited_by_count(String cited_by_count) {
this.cited_by_count = cited_by_count;
}
public String getcitation_count() {
return citation_count;
}
public void setcitation_count(String citation_count) {
this.citation_count = citation_count;
}
public String getaffiliation() {
return affiliation;
}
public void setaffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getgive_name() {
return give_name;
}
public void setgive_name(String give_name) {
this.give_name = give_name;
}
public String getclassification() {
return classification;
}
public void setclassification(String classification) {
this.classification = classification;
}
public String getpublication_start() {
return publication_start;
}
public void setpublication_start(String publication_start) {
this.publication_start = publication_start;
}
public String getpublication_end() {
return publication_end;
}
public void setpublication_end(String publication_end) {
this.publication_end = publication_end;
}
}
And you need a model in the context of MVC, holding all entries:
public class Modelo {
private List<ModeloEntry> entries = new ArrayList<>();
public void addEntry(ModeloEntry entry) {
this.entries.add(entry);
}
public List<ModeloEntry> getEntries() {
return entries;
}
}
Then you can do the following:
public class Main() {
// ...
private static Modelo llenarDatosModelo() {
Modelo autor = new Modelo(); // Create the MVC model first
JSONParser jsonParser = new JSONParser ();
try(FileReader reader = new FileReader ("datos.json")) {
JSONObject documento = (JSONObject) jsonParser.parse(reader);
JSONObject resultados = (JSONObject)documento.get("search-results");
JSONArray Entrys = (JSONArray) resultados.get("entry");
for(Object Entry: Entrys) {
ModeloEntry entry = mostrarInformacionEntry ((JSONObject) Entry); // Create a entry instance per JSON array entry
author.addEntry(entry); // Add the entry to your MVC model
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ParseException e) {
e.printStackTrace();
}
return autor; // Return your MVC model
}
private static ModeloEntry mostrarInformacionEntry(JSONObject entry) {
ModeloEntry entry = new ModeloEntry(); // Create a entry instance
entry.setId((String) entry.get("dc:identifier"));
return entry;
}
}
Your for-each loop is then outsourced to your controller class:
public class Controlador {
private Vista vista;
private Modelo modelo;
public void actualizarVista() {
// Print each entry of your MVC model line by line
for(ModeloEntry entry : modelo.getEntries()) {
vista.imprimirDatos(modelo.getID(),modelo.geturl(), modelo.geteid(), modelo.getdocument_count(), modelo.getcited_by_count(), modelo.getcitation_count(), modelo.getaffiliation(), modelo.getgive_name(), modelo.getclassification(), modelo.getpublication_start(), modelo.getpublication_end());
}
}
}
My program is meant to be a banking application. When you start it you can either create a customer or login in as an existing user. For now i can only use customers which i create during the time i run my program but want my program to save the customers even after the program has been closed.
My problem: after creating a customer i close the program-> restart it and try to log in but i get an error: "java.lang.ClassCastException: java.lang.String cannot be cast to nictho7.Customer
at nictho7.GUI$AL.actionPerformed(GUI.java:221)" this row is mine "nictho7.Customer a = (nictho7.Customer) infil.readObject();" below.
"Customer" is a class for my custmers has name,surname & ID.
"bang" is short for my logic class where i store this file.
I reason that the program read from my file searching for object that resembles Customer saves them to the variable "a" and if that variable has an ID which equals the text a user enters it should be fine? But obviously there is something that I'm missing, or maybe sevral things...
**update 12-30
I want to add my customers to a list - customers contains:name,surname,ID & array of diffrent accounts(cred/savings).
when i create and run this "new" code(compared to my original post) i get an IOException but I can now access the customer account through the list i created, how can i get rid of that IOException?
2.After adding a creditaccount to my customer i close the program and restart it, when i try to login i recieve this message: >
java.lang.ClassCastException: java.lang.Boolean cannot be cast to nictho7.Customer
at nictho7.GUI$AL.actionPerformed(GUI.java:224)<
I understand what Java is telling me, >a boolean can not be cast to a customer cuz my customer does not contain any boolean< but I fail to see where i am trying to do so and how I could fix this?
Line 224 is my refering to the code in my try{ while(true)-loop: a = (Customer) infil.readObject();`
if (ClickedButton == kund) {
// JTextField username = new JTextField();
JTextField ID = new JTextField();
// med ok-och avbrytknapp inbyggd
Object[] message = { "Personal identity number:", ID, };
int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
Customer = ID.getText();
// if ((bang.searchCustomer(ID.getText()) != null)) {
// System.out.println("Login successful");
//
// JFrame frame = new customer();
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setTitle("Bank");
// frame.setVisible(true);
// }
if (bang.data.exists()) {
ObjectInputStream infil = null;
try {
infil = new ObjectInputStream(new FileInputStream("C:\\Users\\nickt\\eclipse-workspace\\nictho7\\Bankdata.dat"));
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "IOEfil");
e1.printStackTrace();
} catch (ClassCastException e1) {
JOptionPane.showMessageDialog(null, "classcast111111");
e1.printStackTrace();
}
try {
while (true) {
Customer a = new Customer();
a = (Customer) infil.readObject();
bang.customers.add( a );
if (infil != null) {
infil.close();
}
}
} catch (ClassNotFoundException e1) {
JOptionPane.showMessageDialog(null, "File not found");
e1.printStackTrace();
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "IOEinlasning");
e1.printStackTrace();
} catch (ClassCastException e1) {
JOptionPane.showMessageDialog(null, "classcast");
e1.printStackTrace();
}finally {
// Close the ObjectInputStream
try {
if (infil != null) {
infil.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
if ((bang.searchCustomer(ID.getText()) != null)) {//(a.getPersonalNumber() == ID.getText()) {
System.out.println("Login successful");
JFrame frame = new customer();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Bank");
frame.setVisible(true);
}
}
}
Customer
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Customer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int Arraylist = 0;
// ------- Instansvariabler ----------
private String name;
private String surname;
private String personalNumber;
public Customer() {
super();
accounts = new ArrayList<>(); // credit och saving finns med i denna lista.
}
// ------- lista med konton ----------
public ArrayList<Account> accounts;
// ------- Konstruktör ----------
public Customer(String cName, String surName, String pNumber, ArrayList<Account> a) {
name = cName;
surname = surName;
personalNumber = pNumber;
accounts = a;
}
// ------- Get- & set-metoder ----------
public String getCustomer() {
return name + " " + surname + " " + personalNumber;
}
public String getCustomerSurname() {
return surname;
}
public void setCustomerSurname(String customerSurname) {
surname = customerSurname;
}
public String getcustomerName() {
return name;
}
public void setcustomerName(String customerName) {
name = customerName;
}
public String getPersonalNumber() {
return personalNumber;
}
public void setPersonalNumber(String PersonalNumber) {
personalNumber = PersonalNumber;
}
public ArrayList<Account> getAccountList() {
return accounts;
}
// void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
// {
// name = (String) in.readObject();
// surname = (String) in.readObject();
// personalNumber = (String) in.readObject();
// }
private void readObject(
ObjectInputStream in
) throws ClassNotFoundException, IOException {
//always perform the default de-serialization first
in.defaultReadObject();
name = getcustomerName();
//ensure that object state has not been corrupted or tampered with maliciously
// validateState();
}
}
Account
import java.util.Random;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
public abstract class Account implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
// ------- Instansvariabler ----------
private double interestRate;
private double balance;
private int accountNumber;
private static int lastassignedNumber = 1001;
private double debtRate = 7;
private String accType;
private double credLimit;
// lista för transaktioner och variabel för tid.
protected ArrayList<String> transactionsList = new ArrayList<String>();
// random datum för transaclist
Random rnd = new Random();
// Date date = new Date(Math.abs(System.currentTimeMillis() - rnd.nextInt()));
// default konto
public Account() {
setAccountNumber(getlastassignedNumber());
}
// Presentationsmetoder
public double Withdraw(Account a, double amount) {
a.setBalance(a.getBalance() - amount);
return getBalance();
}
public double Deposit(Account a, double amount) {
a.setBalance(a.getBalance() + amount);
return a.getBalance();
}
public static int getLastassignedNumber() {
return lastassignedNumber;
}
public void setAccountNumber(int d) {
this.accountNumber = d;
}
public double TransactionToAnotherAcc(Account Acc1, Account Acc2, double amount) {
if (Acc1.getBalance() > amount) {
Acc2.setBalance(Acc2.getBalance() + amount);
Acc1.setBalance(Acc1.getBalance() - amount);
double a = Acc1.getBalance();
return a;
}
else
System.out.print("Your requested amount cannot be transactioned due to insufficient funds");
return 0;
}
protected abstract String getspecinfo();
public String getinfo() {
return getcommoninfo() + getspecinfo();
}
public String getcommoninfo() {
String info = accountNumber + " " + getBalance();
return info;
}
// ------- Get-metoder ----------
public double getRate(double balance) {
double interestrate = balance / interestRate;
return interestrate;
}
public void getbalance(int balance) {
this.balance = balance;
}
public int getAccountNumber() {
return accountNumber;
}
public int getlastassignedNumber() {
accountNumber = lastassignedNumber;
++lastassignedNumber;
return accountNumber;
}
public String getAccount() {
return accountNumber + " " + getBalance();
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getInterestRate() {
return interestRate;
}
public void setInterestRate(double interestRate) {
this.interestRate = interestRate;
}
public ArrayList<String> getTransactionsList() {
return transactionsList;
}
public String inreturnintrest(double d) {
if (d < 0) {
d = (d * 7) / 100;
String info1 = debtRate + " " + d;
return info1;
}
else
d = (d * (0.5 / 100));
String info2 = interestRate + " " + d;
return info2;
}
public String getAccType() {
return accType;
}
public void setAccType(String accType) {
this.accType = accType;
}
public double getCredLimit() {
return credLimit;
}
public void setCredLimit(double credLimit) {
this.credLimit = credLimit;
}
// private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
// {
// interestRate = (double) in.readObject();
// balance = (double) in.readObject();
// accountNumber = (int) in.readObject();
// lastassignedNumber = ( int ) in.readInt();
// debtRate = (double) in.readObject();
// accType = (String) in.readObject();
// credLimit = (double) in.readObject();
//
// }
private void readObject(
ObjectInputStream in
) throws ClassNotFoundException, IOException {
//always perform the default de-serialization first
in.defaultReadObject();
//make defensive copy of the mutable Date field
// fDateOpened = new Date(fDateOpened.getTime());
//ensure that object state has not been corrupted or tampered with maliciously
// validateState();
}
}
Functions in my Logic-class to call the functions im trying to fix
public int createSavingsAccount(String pNr) {
for (int i = 0; i < customers.size(); i++) {
if ((customers.get(i).getPersonalNumber()).equals(pNr)) {
SavingAccount newaccount = new SavingAccount();
customers.get(i).accounts.add(newaccount); // saccounts
return newaccount.getAccountNumber();
}
}
return -1;
}
public boolean createCustomer(String name, String surename, String pNr, ArrayList<Account> b) throws FileNotFoundException, IOException {
boolean createCustomer = true;
b = new ArrayList<>();
#SuppressWarnings({ })
ObjectOutputStream utfil = new ObjectOutputStream (new FileOutputStream(data));
for (int i = 0; i < customers.size(); i++) {
if ((customers.get(i).getPersonalNumber()).equals(pNr)) {
createCustomer = false;
}
}
if (createCustomer != false) {
customers.add(new Customer(name, surename, pNr, b));
//sparar kunden som objekt för loggin
Customer a = new Customer (name, surename, pNr,b);
createCustomer = true;
//name = (String)
utfil.writeObject(a);
//surename = (String)
// utfil.writeObject(surename);
//pNr = (String)
// utfil.writeObject(pNr);
// utfil.writeObject(b);
utfil.writeObject(a);
utfil.close();
}
return createCustomer;
}
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.
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
I have to delete the last row from the database (created with MySQL) using .remove and .flush but it keeps telling me that the row is not deleted. I have tried to write it different ways yet I can't seemm to get it to work. Any help would be appreciated! Here is the code:
package com.vz.test.mbean;
import com.vz.test.db.Person;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#ManagedBean
#ViewScoped
public class AddPerson {
com.vz.test.db.Person person = null;
private int identification = 0;
private String name = "";
private String age = "";
private String telephone = "";
private String results="";
private java.util.List<Person> alst = new java.util.ArrayList<Person>();
public java.util.List<Person> getAlst() {
return alst;
}
public void setAlst(ArrayList<Person> alst) {
this.alst = alst;
}
public String getResults() {
return results;
}
public void setResults(String results) {
this.results = results;
}
#PersistenceContext(unitName = "WebApplication2PU")
private EntityManager em;
#Resource
private javax.transaction.UserTransaction utx;
public int getIdentification() {
return identification;
}
public void setIdentification(int identification) {
this.identification = identification;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public AddPerson() {
}
public void fetchPersonList(){
Query qu = em.createQuery("SELECT a FROM Person a");
alst= (java.util.List<Person>) q.getResultsList();
System.out.println("alst.size():"+ alst.size());
}
public void addRow() {
try {
System.out.println("I am in addRow");
com.vz.test.db.Person person = new com.vz.test.db.Person();
person.setName(name);
person.setAge(age);
person.setTelephone(telephone);
persist(person);
result="Row is added";
}
catch (Exception e) {
result="Row is NOT added";
}
}
public void deleteRow(){
try{
em.remove(person);
em.flush();
persist(person);
result="Row is deleted";
}
catch (Exception e){
result="Row is NOT deleted";
}
}
public void persist(Object object) {
try {
utx.begin();
em.persist(object);
utx.commit();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
throw new RuntimeException(e);
}
}
}
em.remove(person);
em.flush();
persist(person);
You first remove the entity and try to persist it afterwards. Wrap the remove call in a user transaction instead, that should solve the problem:
try {
if (person != null) {
utx.begin();
em.remove(person);
utx.commit();
result="Row is deleted";
} else {
System.out.println("The field 'person' is null. Can't remove anything");
}
}
catch (Exception e) {
// TODO add proper exception handling/logging
result="Row is NOT deleted";
}