Create a simple system to students and subjects - java

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("---------------------------------");
}

Related

Problem trying to read a json file in Java with the MVC pattern

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());
}
}
}

Neodatis and duplicities

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.

Handle deep nested complex xml with FreeMarker

This is a part of a complex xml template which i put here for the question :
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgId>${MsgId}</MsgId>
<CreDtTm>${CreDtTm}</CreDtTm>
<NbOfTxs>${NbOfTxs}</NbOfTxs>
<a> ${val1}
<b>
${val2}
</b>
</a>
<CtrlSum>${CtrlSum}</CtrlSum>
</GrpHdr>
<PmtInf>
<PmtInfId>${PmtInfId}</PmtInfId>
<PmtMtd>${PmtMtd}</PmtMtd>
</PmtInf>
<#list persons as person>
</#list>
</CstmrDrctDbtInitn>
</Document>
I have been using FreeMarker for the previous month and until now the xml models have been easy
Searching over the web on how to approach this template , should i create matching java classes (100 of them ? )... should i use Map? like shown here .
I don't have a clue how to do it ... how to apply FreeMarker on this template ?
So here is a solution for any future users . Firstly i created 3 models which i am calling like below :
Map<String, Object> data = new HashMap<>();
//================= Example Creating HeaderVo //=================
HeaderVo header = new HeaderVo("la","la",5,5,"la","la");
data.put("header", header);
//================= Example Creating MiddleVo //=================
MiddleVo middleVo = new MiddleVo("la","la",5,"la","la","la","la");
data.put("middle", middleVo);
//================= Example Creating internal items =================
InternalVo v1 = new InternalVo(5, 5, 5, "s", true, "zz", "zzzz", "ll","EUR");
InternalVo v2 = new InternalVo(5, 5, 5, "s", true, "zz", "zzzz", "ll","DOLLARS");
InternalVo v3 = new InternalVo(5, 5, 5, "s", true, "zz", "zzzz", "ll","LAT");
//List parsing
List<InternalVo> internalVos = new ArrayList<>();
internalVos.add(v1);
internalVos.add(v2);
internalVos.add(v3);
data.put("vos", internalVos);
//================= //================= //================= //=================
final String message = this.templateManager.composeStringFromTemplate(data, "bankfile.ftl");
So below is the bankfile.ftl which represents the complex xml :
```
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02">
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgId>${header.msgId}</MsgId>
<CreDtTm>${header.creDtTm}</CreDtTm>
<NbOfTxs>${header.nbOfTxs}</NbOfTxs>
<CtrlSum>${header.ctrlSum}</CtrlSum>
<InitgPty>
<Nm>${header.nm}</Nm>
<Id>
<OrgId>
<Othr>
<Id>${header.id}</Id>
</Othr>
</OrgId>
</Id>
</InitgPty>
</GrpHdr>
<PmtInf>
<PmtTpInf>
<SvcLvl>
<Cd>${middle.svcLvlCD}</Cd>
</SvcLvl>
<LclInstrm>
<Cd>${middle.lclInstrmCD}</Cd>
</LclInstrm>
<SeqTp>${middle.seqTp}</SeqTp>
</PmtTpInf>
<ReqdColltnDt>${middle.reqdColltnDt}</ReqdColltnDt>
<Cdtr>
<Nm>${middle.nm}</Nm>
</Cdtr>
<CdtrAcct>
<Id>
<IBAN>${middle.iBAN}</IBAN>
</Id>
</CdtrAcct>
<CdtrAgt>
<FinInstnId>
<BIC>${middle.bIC}</BIC>
</FinInstnId>
</CdtrAgt>
<#list vos as vo>
<DrctDbtTxInf> <PmtId> <EndToEndId>${vo.endToEndId}</EndToEndId> </PmtId> <InstdAmt Ccy="${vo.ccy}">${vo.instdAmt}</InstdAmt> <DrctDbtTx> <MndtRltdInf> <MndtId>${vo.mndtId}</MndtId> <DtOfSgntr>${vo.dtOfSgntr}</DtOfSgntr> <AmdmntInd>${vo.amdmntInd?c}</AmdmntInd> </MndtRltdInf> </DrctDbtTx> <DbtrAgt> <FinInstnId> <BIC>${vo.bIC}</BIC> </FinInstnId> </DbtrAgt> <Dbtr> <Nm>${vo.nm}</Nm> </Dbtr> <DbtrAcct> <Id> <IBAN>${vo.iBAN}</IBAN> </Id> </DbtrAcct> </DrctDbtTxInf>
</#list>
</PmtInf>
</CstmrDrctDbtInitn>
</Document>
```
And finally here are the 3 models used for the FTL ( sorry for them being huge , i just wanted to so how complex it can get :) ):
HeaderVo
public class HeaderVo {
private String msgId;
private String creDtTm;
private int nbOfTxs;
private int ctrlSum;
private String nm;
private String id;
public HeaderVo() {
super();
}
public HeaderVo(String msgId, String creDtTm, int nbOfTxs, int ctrlSum, String nm, String id) {
super();
this.msgId = msgId;
this.creDtTm = creDtTm;
this.nbOfTxs = nbOfTxs;
this.ctrlSum = ctrlSum;
this.nm = nm;
this.id = id;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getCreDtTm() {
return creDtTm;
}
public void setCreDtTm(String creDtTm) {
this.creDtTm = creDtTm;
}
public int getNbOfTxs() {
return nbOfTxs;
}
public void setNbOfTxs(int nbOfTxs) {
this.nbOfTxs = nbOfTxs;
}
public int getCtrlSum() {
return ctrlSum;
}
public void setCtrlSum(int ctrlSum) {
this.ctrlSum = ctrlSum;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
MiddleVo
public class MiddleVo {
private String svcLvlCD;
private String lclInstrmCD;
private int seqTp;
private String reqdColltnDt;
private String nm;
private String iBAN;
private String bIC;
public MiddleVo() {
super();
}
public MiddleVo(String svcLvlCD, String lclInstrmCD, int seqTp, String reqdColltnDt, String nm, String iBAN,
String bIC) {
super();
this.svcLvlCD = svcLvlCD;
this.lclInstrmCD = lclInstrmCD;
this.seqTp = seqTp;
this.reqdColltnDt = reqdColltnDt;
this.nm = nm;
this.iBAN = iBAN;
this.bIC = bIC;
}
public String getSvcLvlCD() {
return svcLvlCD;
}
public void setSvcLvlCD(String svcLvlCD) {
this.svcLvlCD = svcLvlCD;
}
public String getLclInstrmCD() {
return lclInstrmCD;
}
public void setLclInstrmCD(String lclInstrmCD) {
this.lclInstrmCD = lclInstrmCD;
}
public int getSeqTp() {
return seqTp;
}
public void setSeqTp(int seqTp) {
this.seqTp = seqTp;
}
public String getReqdColltnDt() {
return reqdColltnDt;
}
public void setReqdColltnDt(String reqdColltnDt) {
this.reqdColltnDt = reqdColltnDt;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getiBAN() {
return iBAN;
}
public void setiBAN(String iBAN) {
this.iBAN = iBAN;
}
public String getbIC() {
return bIC;
}
public void setbIC(String bIC) {
this.bIC = bIC;
}
}
InternalVo
public class InternalVo {
private int endToEndId;
private int instdAmt;
private int mndtId;
private String dtOfSgntr;
private boolean amdmntInd;
private String bIC;
private String nm;
private String iBAN;
private String ccy;
public InternalVo() {
super();
}
public InternalVo(int endToEndId, int instdAmt, int mndtId, String dtOfSgntr, boolean amdmntInd, String bIC, String nm,
String iBAN,String ccy) {
super();
this.endToEndId = endToEndId;
this.instdAmt = instdAmt;
this.mndtId = mndtId;
this.dtOfSgntr = dtOfSgntr;
this.amdmntInd = amdmntInd;
this.bIC = bIC;
this.nm = nm;
this.iBAN = iBAN;
this.ccy = ccy;
}
public int getEndToEndId() {
return endToEndId;
}
public void setEndToEndId(int endToEndId) {
this.endToEndId = endToEndId;
}
public int getInstdAmt() {
return instdAmt;
}
public void setInstdAmt(int instdAmt) {
this.instdAmt = instdAmt;
}
public int getMndtId() {
return mndtId;
}
public void setMndtId(int mndtId) {
this.mndtId = mndtId;
}
public String getDtOfSgntr() {
return dtOfSgntr;
}
public void setDtOfSgntr(String dtOfSgntr) {
this.dtOfSgntr = dtOfSgntr;
}
public boolean isAmdmntInd() {
return amdmntInd;
}
public void setAmdmntInd(boolean amdmntInd) {
this.amdmntInd = amdmntInd;
}
public String getbIC() {
return bIC;
}
public void setbIC(String bIC) {
this.bIC = bIC;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
public String getiBAN() {
return iBAN;
}
public void setiBAN(String iBAN) {
this.iBAN = iBAN;
}
public String getCcy() {
return ccy;
}
public void setCcy(String ccy) {
this.ccy = ccy;
}

How can I set My Json Value in Adapter

I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();

Linked lists, students to a subject

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.

Categories

Resources