Can't call method from another class in Java - java

I'm new to Java and honestly its OOP focus is quite taxing for me at the moment.
For an Uni project where we're meant to practice this focus, I'm tasked with creating at least 2 classes:
One class should be for an airline customer and the other class should contain methods to register their purchase.
I have a main file, a Persona (Person) class, and a RegistroCompra (Purchase registration) class. Person is supposed to have all of the following attributes, which I'm handling as private variables so that every instance of Person can get one of their own.
(The attributes being asked for are stuff like personal data, ticket number, seat number and such)
public class Persona {
private String nombrePasajero;
private String apellidoPasajero;
private String generoPasajero;
private String pasaportePasajero;
private String numTiquetePasajero;
private String numVueloPasajero;
private String destinoPasajero;
private String asientoString;
private int precioBoleto;
private int edadPasajero;
private int numAsientoPasajero;
//Constructor
public Persona(String nombre, String apellido, String genero, int edad, String pasaporte) {
nombrePasajero = nombre;
apellidoPasajero = apellido;
generoPasajero = genero;
pasaportePasajero = pasaporte;
edadPasajero = edad;
}
public void setDestino() {
destinoPasajero = RegistroCompra.obtenerDestino();
}
And my RegistroCompra class, which is meant to set the data related not to personal information but to the information of destination, flight number and such. All of the data set in RegistroCompra has to be fetched by Persona, because only Persona will be printed in main to verify all of the information.
public class RegistroCompra {
private String destino;
public void seleccionarDestino() {
Scanner input = new Scanner(System.in);
System.out.println("Por favor digite el destino, las opciones actuales son Nicaragua o Panama\n");
String destino = input.nextLine();
}
public String obtenerDestino() {
return destino;
}
}
However, I get an error at the Persona.setDestino() method, saying "non-static method obtenerDestino cannot be referenced from astatic context"
I don't understand why this is going on. If I try to turn RegistroCompra.obtenerDestino() into a static method, I get an error because "destino is a non static variable", but it's being defined as public in the RegistroCompra class...

You have to do something like below:
public class Persona {
...
//You should have instance of RegistroCompra
RegistroCompra registraCompra = new RegistroCompra();
public void setDestino() {
//Option 1: Explicitly call the method
registraCompra.seleccionarDestino();
destinoPasajero = registraCompra.obtenerDestino();
}
}
public class RegistroCompra {
private String destino;
public RegistroCompra(){
//Option 2 : Call the method in constructor
registraCompra();
}
public void seleccionarDestino() {
...
//Set the input to the class level variable destino
this.destino = input.nextLine();
}
public String obtenerDestino() {
return this.destino;
}
}

You can do this making destino variable and obtenerDestino() method static. Check the below changes to RegistroCompra class:
public class RegistroCompra {
private static String destino;
public void seleccionarDestino() {
Scanner input = new Scanner(System.in);
System.out.println("Por favor digite el destino, las opciones actuales son Nicaragua o Panama\n");
String destino = input.nextLine();
}
public static String obtenerDestino() {
return destino;
}
}

You are calling an instance method without having an instance. You have to instantiate the class (create an instance from that class) before you are able to call instance methods.

Related

Adding a new object to an ArrayList that is an attribute of another class

I am getting an error when trying to add a new object to an ArrayList that is an attribute of another class. Let me explain.
UML
I do have 2 classes in my model:
Equipo
Jugador
To simplify things let's call Equipo -> Team & Jugador -> Player.
For each Team there will be multiple players, so I have created an ArrayList of type Player as an attribute in the Team class.
Equipo
public class Equipo {
private String nombre;
private LocalDate fechaAlta;
private String continente;
private char clasificado;
private ArrayList <Jugador> listaJugadores; //Muestra la relación
public Equipo(String nombre, LocalDate fechaAlta, String continente, char clasificado) {
this.nombre = nombre;
this.fechaAlta = fechaAlta;
this.continente = continente;
this.clasificado = clasificado;
}
.
.
.
}
Jugador
public class Jugador {
private String jugador;
private int dorsal;
public Jugador(String jugador, int dorsal) {
this.jugador = jugador;
this.dorsal = dorsal;
}
.
.
.
}
MAIN
In the main class I have created and initialized the Teams and Players ArrayLists.
public static Ventana v1;
public static ArrayList <Equipo> listaEquipos;
public static ArrayList <Jugador> listaJugadores;
public static void main(String[] args) {
v1 = new Ventana();
v1.getearComboBox();
v1.setVisible(true);
//Inicializar arrays
listaEquipos = new ArrayList <Equipo>();
listaJugadores = new ArrayList <Jugador>();
I am trying to add a Player to the last Team in the Array
public static void inscribirJugador(String nombreJugador, String dorsalString){
//Conversion del dorsal
int dorsal = Integer.parseInt(dorsalString);
listaEquipos.get(listaEquipos.size()-1).getListaJugadores().add(new Jugador("nombreJugador", dorsal));
}
However I am getting this NullPointerException error that I am not being able to solve.
https://imgur.com/a/Fc6ehlu
LINE 98: listaEquipos.get(listaEquipos.size()-1).getListaJugadores().add(new Jugador("nombreJugador", dorsal));
If you did not put at least a team in the ArrayList, you are calling getListaJugadores on a null object.
In fact, if the ArrayList listaEquipos is empty, you will return null on the method invocation listaEquipos.get(listaEquipos.size() -1). You got to have at least one team to retrieve the list of players!

Why I can't instantiate an Object like this? [duplicate]

This question already has answers here:
Instantiating inner class
(3 answers)
Closed 4 years ago.
I have already make a class "CdFilm" in different file with main class. But I can't instantiate the new object with my own class. I instantiate it like this :
FileRentalVCD.CdFilm film = new FileRentalVCD.CdFilm(1);
This is the class "CdFilm" file :
public class FileRentalVCD {
private String judul, publisher;
private char kategori;
private int stok;
public class CdFilm {
//inheritance from FileRentalVCD
private String judul, publisher;
private char kategori;
private int stok;
//atribut class CDFilm
private String pemain, sutrdara;
//constructor
public CdFilm (int s) {
this.stok = s;
}
//methods encapsulation
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
}
}
And this is the main class, where i instantiate my object :
public class RentalVCD {
public void EntriCdFilm (FileRentalVCD.CdFilm input) {
Scanner scan = new Scanner(System.in);
System.out.println("Masukan Judul : ");
String judul = scan.next();
input.setJudul(judul);
}
public static void main(String[] args) {
System.out.println("Rental VCD Alif");
System.out.println("1. Entri data CdFilm");
System.out.println("2. Entri data CdMusik");
System.out.println("3. Tampilkan data CdFilm");
System.out.println("4. Tampilkan data CdMusik");
Scanner scan = new Scanner(System.in);
int pilihan = scan.nextInt();
FileRentalVCD.CdFilm film = new FileRentalVCD.CdFilm(1);
}
}
You can, just not with that syntax. It's somewhat counter-intuitive, but you can use the following to create an instance of your inner class:
FileRentalVCD.CdFilm film = new FileRentalVCD(/* add any args here */).new CdFilm(1);
This is needed because you need an instance of your outer class to create an instance of the inner class.

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

How to use Arraylist over different classes

Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.
First class:
public class Hund {
private String namn;
private int ålder;
private double vikt;
private String ras;
public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
this.namn = hundnamn;
this.ålder = hundålder;
this.ras = hundras;
this.vikt = hundvikt;
}
public String getNamn() {
return namn;
}
public int getÅlder() {
return ålder;
}
public double getSvanslängd() {
if (ras=="tax"){
return 3.7;
}else{
return ((vikt*ålder)/10);
}
}
public String toString() {
return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
}
}
Second Class
import java.util.ArrayList;
public class testning {
public static void main(String[] args) {
Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
System.out.println(nyHund.toString());
Register.läggTillHund(nyHund);
}
}
And the Third class:
import java.util.ArrayList;
public class Register {
public static void läggTillHund(Hund nyHund){
hundRegister.add(nyHund);
System.out.println(nyHund);
}
private Register(){
ArrayList<Hund> hundRegister = new ArrayList<Hund>();
}
}
The problem i am experiencing is with "hundRegister.add(nyHund)"
any thoughts? or pointers where im going wrong? (very new at Java)
Best Regards
Oskar
The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.
public class Register {
private ArrayList<Hund> hundRegister;
private Register(){
hundRegister = new ArrayList<Hund>();
}
}
Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.
Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.

Abstract factory Builder

Below is my Builder pattern class which generates an Employee Object.
public class Employee {
// required parameters
private String HDD;
private String RAM;
// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
private Employee(EmployeeBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}
public static class EmployeeBuilder {
private String HDD;
private String RAM;
// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public EmployeeBuilder(String hdd, String ram){
this.HDD = hdd;
this.RAM = ram;
}
public EmployeeBuilder isGraphicsCardEnabled(Boolean isGraphicsCardEnabled){
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}
public EmployeeBuilder isBluetoothEnabled(boolean isBluetoothEnabled){
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}
public Employee build(){
return new Employee(this);
}
}
public static void main(String args[]){
Employee emp = new Employee.EmployeeBuilder("500", "64").
isGraphicsCardEnabled(true).
isGraphicsCardEnabled(true).build();
System.out.println(emp.HDD);
System.out.println(emp.getHDD());
}
}
A builder whose parameters have been set makes a fine Abstract Factory [Gamma95, p. 87]. In other words, a client can pass such a builder to a method to enable the method to create one or more objects for the client. To enable this usage, you need a type to represent the builder. If you are using release 1.5 or a later release, a single generic type (Item 26) suffices for all builders, no matter what type of object they’re building.
Can anyone add some light on the above paragraph with an working example. I am not able to understand the above para which is taken from Effective Java - Joshua Bloch.

Categories