I just started to learn Java and i think this a very basic question but i didn't find the right answer yet so i try in here.
I just want to show in my console the names and descriptions of some animals, but i don't know how to manipulate variables from a class of a class.
I guess i have to use parameters but i don't find how to use them in a class...
My "Animal.java"
public class Animal {
private String nom;
public static String DESCRIPTION;
public String toString(){
return "Je suis " + this.nom;
}
public void direNom(){
System.out.println(toString());
}
public void direDESCRIPTION(){
System.out.println("Description: " + this.DESCRIPTION);
}
public String getNom(){
return nom;
}
public void setNom(String nom){
this.nom = nom;
}
class Vertebre{
int nbrVertebre;
class Mammifere{
class Ours{
String nom = "Poumba";
String DESCRIPTION = "Description de Poumba";
}
class Chimpanze{
String nom = "Cheeta";
String DESCRIPTION = "Description de Cheeta";
}
class Rats{
String nom = "Ratata";
String DESCRIPTION = "Description de Ratata";
}
}
class Poisson{
class Requins{
String nom = "Jaws";
String DESCRIPTION = "Description de Jaws";
}
class Raies{
String nom = "Raimonta";
String DESCRIPTION = "Description de Raimonta";
}
class Truites{
String nom = "Truita";
String DESCRIPTION = "Description de Truita";
}
}
class Reptile{
class Tortue{
String nom = "Tortega";
String DESCRIPTION = "Description de Tortega";
}
class Serpent{
String nom = "Serpento";
String DESCRIPTION = "Description de Serpento";
}
}
}
}
My "TestZoo.java"
public class TestZoo {
public static void main(String[] args){
Animal unAnimal = new Animal();
unAnimal.setNom("Jaws");
unAnimal.direNom();
unAnimal.direDESCRIPTION();
unAnimal.setNom("Cheeta");
unAnimal.direNom();
unAnimal.direDESCRIPTION();
unAnimal.setNom("Ham");
unAnimal.direNom();
unAnimal.direDESCRIPTION();
}
}
Try this:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone{
public static void main(String []args){
Ours poumba = new Ours();
poumba.direNom();
}
}
class Animal {
protected String nom;
public String toString(){
return "Je suis " + this.nom + ", je suis un " + this.getClass();
}
public void direNom(){
System.out.println(toString());
}
public String getNom(){
return nom;
}
public void setNom(String nom){
this.nom = nom;
}
}
class Vertebre extends Animal {
int nbrVertebre;
}
class Mammifere extends Vertebre {}
class Ours extends Mammifere {
public Ours(){
this.setNom("Poumba");
}
}
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());
}
}
}
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.
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("---------------------------------");
}
Having issue of getting object from other class file...
This function let us take in the title (from movie class) and name (from theatre class).
2 input from user asking what is the title and name, from there we need to take in an movie object and theatre object to check is the title can be found in the movie class. same to name in theatre class.
public MovieScreening(Movie movieObject,Theatre theatreObject){
this.movieObject = movieObject;
this.theatreObject = theatreObject;
}
public Movie getMovieObject() {
return movieObject;
}
public Theatre getTheatreObject() {
return theatreObject;
}
Your code is wrong and incomplete, so I can barely have an idea of what do you want here.
But maybe, this code below can help you somehow. Please state better questions.
import java.util.ArrayList;
public class Screener {
private static ArrayList <MovieScreening> screenings = new ArrayList <MovieScreening>();
/**
* #param args
*/
public static void main(String[] args) {
String movie = "Titanic";
String theatre = "Cineplex";
screenings.add(new MovieScreening(new Movie("Titanic"),new Theatre("Odeon")));
screenings.add(new MovieScreening(new Movie("run lola run"),new Theatre("Cineplex")));
screenings.add(new MovieScreening(new Movie("Titanic"),new Theatre("Cineplex")));
for(MovieScreening s:screenings){
if(s.contains(movie,theatre)){
System.out.println("Added successfully:"+s);
} else {
System.out.println("Your movie or/and theatre cannot be found:"+s);
}
}
}
}
and
public class MovieScreening {
private Movie movie;
private Theatre theatre;
public MovieScreening(Movie movie, Theatre theatre) {
this.movie = movie;
this.theatre = theatre;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public Theatre getTheatre() {
return theatre;
}
public void setTheatre(Theatre theatre) {
this.theatre = theatre;
}
public boolean contains(String movie, String theatre) {
return this.movie.getTitle().equals(movie) && this.theatre.getName().equals(theatre);
}
#Override
public String toString() {
return "MovieScreening [movie=" + movie + ", theatre=" + theatre + "]";
}
}
and
public class Theatre {
private String name;
public Theatre(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Theatre [name=" + name + "]";
}
}
and
public class Movie {
private String title;
public Movie(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
#Override
public String toString() {
return "Movie [title=" + title + "]";
}
}
will probably give you an output like this
Your movie or/and theatre cannot be found:MovieScreening [movie=Movie [title=Titanic], theatre=Theatre [name=Odeon]]
Your movie or/and theatre cannot be found:MovieScreening [movie=Movie [title=run lola run], theatre=Theatre [name=Cineplex]]
Added successfully:MovieScreening [movie=Movie [title=Titanic], theatre=Theatre [name=Cineplex]]
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java null pointer exceptions - don't understand why…
MOVIE.JAVA
package javaPractical.week3;
import javax.swing.*;
public class Movie {
// private attributes
private String title;
private String movieURL;
private String year;
private String genre;
private String actor;
// constructor
Movie(String t, String u, String y, String g, String a) {
this.title = t;
this.movieURL = u;
this.year = y;
this.genre = g;
this.actor = a;
}
// getters and setters
public void setTitle(String t) {
this.title = t;
}
public String getTitle() {
return this.title;
}
public void set_url(String a) {
this.movieURL = a;
}
public String get_url() {
return this.movieURL;
}
public void setYear(String y) {
this.year = y;
}
public String getYear() {
return this.year;
}
public void setGenre(String g) {
this.genre = g;
}
public String getGenre() {
return this.genre;
}
public void setActor(String a) {
this.actor = a;
}
public String getActor() {
return this.actor;
}
// output movie details
public String toString() {
return ("Title: " + this.title + "\nURL: " + this.movieURL + "\nYear: "
+ this.year + "\nGenre: " + this.genre + "\nActor: " + this.actor);
}
public static void main(String[] args) {
// testing Movie class
Movie Movie1 = new Movie("Spiderman", "www.", "2002", "Action",
"Tobey M");
JOptionPane.showMessageDialog(null, Movie1.toString());
// testing MovieList class
}
}
MOVIELIST.JAVA
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
public class MovieList1 {
private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
private static int NUM_OF_MOVIES = 10;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies() {
return this.myFavouriteMovies.size();
}
public boolean isEmpty() {
if (this.myFavouriteMovies.isEmpty()) {
return true;
} else
return false;
}
public static void main(String[] args) {
MovieList1 List = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
myFavouriteMovies.add(TempMovie);
}
}
You have defined static attribute private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
But in the constructor you are assigning the null. After that you are invoking calls like myFavouriteMovies.size() which causes NullPointerException
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
Of course it crashes - you've set it to null.
Why on earth didn't you heed the perfectly good advice you received here?
Java null pointer exceptions - don't understand why
You're wasting everyone's time on a trivial question. I'm voting to close.
Try this - it's still heinous, but it runs:
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class MovieList1
{
private static int NUM_OF_MOVIES = 10;
private List<Movie> myFavouriteMovies;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1()
{
this.myFavouriteMovies = new ArrayList<Movie>();
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies()
{
return this.myFavouriteMovies.size();
}
public boolean isEmpty()
{
return this.myFavouriteMovies.isEmpty();
}
public void add(Movie movie)
{
this.myFavouriteMovies.add(movie);
}
#Override
public String toString()
{
return "MovieList1{" +
"myFavouriteMovies=" + myFavouriteMovies +
'}';
}
public static void main(String[] args)
{
MovieList1 movieList = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
movieList.add(TempMovie);
System.out.println(movieList);
}
}
class Movie
{
private String title;
private String url;
private String year;
private String genre;
private String actor;
Movie(String title, String url, String year, String genre, String actor)
{
this.title = title;
this.url = url;
this.year = year;
this.genre = genre;
this.actor = actor;
}
#Override
public String toString()
{
return "Movie{" +
"title='" + title + '\'' +
", url='" + url + '\'' +
", year='" + year + '\'' +
", genre='" + genre + '\'' +
", actor='" + actor + '\'' +
'}';
}
}