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
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());
}
}
}
Actually I have two probles. One of them is that I am getting empty fields in my RSS Reader. I get just:
screenshot
I was trying to found what's wrong with my code and I noticed that method which should read title, describtion and other stuff singly, its reading all of them together. I mean that my String which should have just single object like title, have everyting like: screenshot
And I have no idea why. Can you help me? I know that there's a lot of code but the problem is in reedFeed in RSSFeedParser class.
Main:
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Scanner;
/**
* Created by Maciek on 2015-11-12.
*/
public class ReadTest {
private static Scanner scanner = new Scanner(System.in);
private static RSSList rssList = new RSSList();
private static String url;
public static String righturl;
public static void main(String[] args) throws XMLStreamException, IOException, ClassNotFoundException {
MENU();
}
public static void MENU() throws IOException, ClassNotFoundException, XMLStreamException {
int choice;
System.out.println("MENU:");
System.out.println(" 1 = Wydrukuj RSS");
System.out.println(" 2 = Pokaz liste dodanych RSS");
System.out.println(" 3 = Dodaj link RSS");
System.out.println(" 4 = Usun link RSS");
System.out.println(" 5 = Wydrukuj historie");
System.out.println("5 = zakoncz");
choice = scanner.nextInt();
switch (choice) {
case 1:
rssList.readCurrentlyList();
printRSS();
MENU();
break;
case 2:
rssList.readCurrentlyList();
printList();
MENU();
break;
case 3:
rssList.readCurrentlyList();
rssList.readHistory();
feedURL();
checkCurrentyList();
rssList.saveCurrentlyList();
MENU();
break;
case 4:
rssList.readCurrentlyList();
System.out.println("Ktory link chcesz usunac?");
printList();
deleteIndex();
rssList.saveCurrentlyList();
MENU();
break;
case 5:
rssList.readHistory();
readHistory();
MENU();
break;
}
}
public static void printRSS() throws XMLStreamException {
for (int i = 0; i < rssList.RSSList.size(); i++) {
righturl = rssList.RSSList.get(i);
RSSFeedParser parser = new RSSFeedParser(righturl);
Feed feed = parser.readFeed();
System.out.println(feed);
for (FeedMessage message : feed.getMessages()) {
System.out.println(message);
}
}
}
public static void printList(){
for(int i = 0; i<rssList.RSSList.size(); i++){
System.out.println(i+1 +". "+rssList.RSSList.get(i));
}
}
public static void deleteIndex(){
int index = scanner.nextInt();
rssList.RSSList.remove(index-1);
}
public static void feedURL(){
scanner.nextLine();
url = scanner.nextLine();
}
public static void addToHistory(){
boolean thereAlreadyIs = false;
for(int i = 0; i<rssList.RSSHistory.size(); i++){
if(rssList.RSSHistory.get(i).equals(url)){
thereAlreadyIs = true;
}
}
if(thereAlreadyIs==false){
rssList.RSSHistory.add(url);
}
}
public static void checkCurrentyList() throws IOException, ClassNotFoundException {
boolean thereAlreadyIs = false;
rssList.readCurrentlyList();
for (int i = 0; i < rssList.RSSList.size(); i++) {
if (url.equals(rssList.RSSList.get(i))) {
thereAlreadyIs = true;
}
}
if (thereAlreadyIs == true) {
System.out.println("Juz jest dodany RSS o takim adresie!");
}
else{
addRSS();
}
}
public static void addRSS(){
rssList.RSSList.add(url);
addToHistory();
}
public static void readHistory() throws IOException, ClassNotFoundException {
rssList.readHistory();
for(int i =0; i<rssList.RSSHistory.size(); i++){
System.out.println("1. "+rssList.RSSHistory.get(i));
}
}
}
Class which collecting reader data.
import java.util.ArrayList;
import java.util.List;
/**
* Created by Maciek on 2015-11-11.
*/
public class Feed {
final String title;
final String description;
final String link;
final String language;
final String copyright;
final String pubDate;
final List<FeedMessage> entries = new ArrayList<FeedMessage>();
public Feed(String title, String description, String link, String language, String copyright, String pubDate){
this.title=title;
this.description=description;
this.link=link;
this.language=language;
this.copyright=copyright;
this.pubDate=pubDate;
}
public List<FeedMessage> getMessages(){
return entries;
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
public String getLink(){
return link;
}
public String getLanguage(){
return language;
}
public String getCopyright(){
return copyright;
}
public String getPubDate(){
return pubDate;
}
public String toString(){
return "Freed: [Title: " +title+", Description: "+description+", Copyright: "+copyright+", Language: "+language+", PubDate: "+pubDate;
}
}
Class which is using to print RSS
public class FeedMessage {
String title;
String description;
String link;
String author;
String guid;
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
public void setDescription(String description){
this.description=description;
}
public String getDescription(){
return description;
}
public void setLink(String link){
this.link=link;
}
public String getLink(){
return link;
}
public void setAuthor(String author){
this.author=author;
}
public String getAuthor(){
return author;
}
public void setGuid(String guid){
this.guid=guid;
}
public String getGuid(){
return guid;
}
public String toString(){
return "FeedMessage: [title= "+title+", Description= "+description+", Link= "+link+", Author: "+author+", Guid= "+guid;
}
}
FeedParser class:
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Created by Maciek on 2015-11-15.
*/
public class RSSFeedParser {
public static final String ITEM = "item";
public static String description = "";
public static String title = "";
public static String link = "";
public static String language = "";
public static String copyright = "";
public static String author = "";
public static String pubDate = "";
public static String guid = "";
public Feed feed;
public boolean isFeedHeader;
public InputStream in;
public XMLInputFactory inputFactory = XMLInputFactory.newInstance();
public XMLEventReader eventReader;
public XMLEvent event;
final URL url;
TITLE tytul = new TITLE();
AUTHOR autor = new AUTHOR();
COPYRIGHT prawa = new COPYRIGHT();
DESCRIPTION opis = new DESCRIPTION();
GUID identyfikacja = new GUID();
LANGUAGE jezyk = new LANGUAGE();
LINK linskon = new LINK();
PUB_DATE publikajca = new PUB_DATE();
ITEM itemson = new ITEM();
public RSSFeedParser(String feedUrl) {
try {
url = new URL(feedUrl);
in = read();
eventReader = inputFactory.createXMLEventReader(in);
event = eventReader.nextEvent();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Feed readFeed() throws XMLStreamException {
try {
isFeedHeader = true;
event = eventReader.nextEvent();
while(eventReader.hasNext()) {
itemson.feedData(this);
tytul.feedData(this);
opis.feedData(this);
System.out.println(description);
linskon.feedData(this);
identyfikacja.feedData(this);
jezyk.feedData(this);
autor.feedData(this);
publikajca.feedData(this);
prawa.feedData(this);
eventReader.close();
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return feed;
}
public Feed setAllElements() throws XMLStreamException {
FeedMessage message = new FeedMessage();
message.setAuthor(author);
message.setDescription(description);
message.setGuid(guid);
message.setLink(link);
message.setTitle(title);
feed.getMessages().add(message);
return feed;
}
private InputStream read() throws XMLStreamException {
try {
return url.openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getCharacterData(XMLEvent event, XMLEventReader eventReader) throws XMLStreamException {
String results = "";
if (event instanceof Characters) {
results = event.asCharacters().getData();
}
return results;
}
}
And I'll paste here just a one of classes which implements after:
public interface Case {
void feedData(RSSFeedParser rss) throws XMLStreamException;
}
Important class is ITEM:
public class ITEM implements Case {
#Override
public void feedData(RSSFeedParser rss) throws XMLStreamException {
if (rss.isFeedHeader) {
rss.isFeedHeader = false;
rss.feed = new Feed(rss.title, rss.link, rss.description, rss.language, rss.copyright, rss.pubDate);
}
rss.event = rss.eventReader.nextEvent();
if (rss.event.isEndElement()) {
if (rss.event.asEndElement().getName().getLocalPart() == (rss.ITEM)) {
try {
rss.setAllElements();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
}
}
and as I said one of these class:
for example title:
public class TITLE implements Case {
#Override
public void feedData(RSSFeedParser rss) throws XMLStreamException {
rss.title = rss.getCharacterData(rss.event, rss.eventReader);
rss.eventReader.close();
}
}
Thanks so much for every help!
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();
}
I have to have the code below, pass the data typed in by the user passed to the following method:
public void addPerson(Person p)
{
personList.add(p);
}
and it must be from there added to the array "personList" that is in databse.java (which is posted at the very bottom.
This is what i have so far:
package hartman;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
handleAddPerson(keyboard);
break;
case "2":
Database.printDatabase();
break;
case "3":
handleSearchPerson(keyboard);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
}
private static void handleAddPerson(Scanner keyboard) {
Printer.printAddPersonTitle();
Printer.printPrompt("First Name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt("Last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt("Social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt("Year Born: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
}
static void handleSearchPerson(Scanner keyboard) {
Printer.printSearchPersonTitle();
Printer.printPrompt(" Enter search value: ");
String keyword = keyboard.nextLine();
}
}
here is Person.java for those who wondered.
package hartman;
public class Person {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private int yearBorn;
public Person() {
}
public Person(String firstName, String lastName,
String socialSecurityNumber, int yearBorn) {
}
public int getAge() {
return yearBorn = 2014 - yearBorn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public int getYearBorn() {
return yearBorn;
}
public void setYearBorn(int yearBorn) {
this.yearBorn = yearBorn;
}
}
and here is database.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
Scanner keyboard = new Scanner(System.in);
private ArrayList<Person> personList;
public Database() {
}
public void addPerson(Person p) {
personList.add(p);
}
public static void printDatabase() {
}
public ArrayList<Person> findPerson(String searchFor) {
Main.handleSearchPerson(keyboard);
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
}
if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
matches.add(p);
}
}
return matches;
}
}
So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
String custPhone) {
super();
this.customerName = customerName;
this.streetAddress = streetAddress;
this.custCity = custCity;
this.custState = custState;
this.custZip = custZip;
this.custPhone = custPhone;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCustCity() {
return custCity;
}
public void setCustCity(String custCity) {
this.custCity = custCity;
}
public String getCustState() {
return custState;
}
public void setCustState(String custState) {
this.custState = custState;
}
public String getCustZip() {
return custZip;
}
public void setCustZip(String custZip) {
this.custZip = custZip;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
}
Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
super();
this.videoName = videoName;
this.videoYear = videoYear;
this.copyNum = copyNum;
this.rentalRate = rentalRate;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public int getVideoYear() {
return videoYear;
}
public void setVideoYear(int videoYear) {
this.videoYear = videoYear;
}
public int getCopyNum() {
return copyNum;
}
public void setCopyNum(int copyNum) {
this.copyNum = copyNum;
}
public double getRentalRate() {
return rentalRate;
}
public void setRentalRate(double rentalRate) {
this.rentalRate = rentalRate;
}
Invoice (incomplete) :
import java.util.Scanner;
public class Invoice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
, "CityVille" , "Alabama" , "18229",
"912-2248");
Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
"Metropolis" , "Pennsylvania" , "24057", "241-8009");
Video Easter = new Video("Easter 2", 2002, 4, 2.49);
Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);
if( Prog4.newRental = "Brandon"){
Customer Brandon = newCust
}
}
}
Prog4(incomplete):
import java.util.*;
public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter Customer Name: ");
String newRental = in.nextLine();
System.out.println("Enter Video Name: ");
String vidName = in.nextLine();
System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();
System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}
public String getNewRental() {
return newRental;
}
public void setNewRental(String newRental) {
this.newRental = newRental;
}
public String getVidName() {
return vidName;
}
public void setVidName(String vidName) {
this.vidName = vidName;
}
public String getRentalDate() {
return rentalDate;
}
public void setRentalDate(String rentalDate) {
this.rentalDate = rentalDate;
}
public String getDaysRented() {
return daysRented;
}
public void setDaysRented(String daysRented) {
this.daysRented = daysRented;
}
}