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

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.

Related

How can my 2nd constructor parameter work?

import java.util.Scanner;
class BloodData{
static Scanner in = new Scanner(System.in);
static String bloodType;
static String rhFactor;
public BloodData(){
bloodType = "O";
rhFactor = "+";
}
public BloodData(String bt, String rh){
bloodType = bt;
rhFactor = rh;
}
public void display() {
System.out.println(bloodType+rhFactor+" is added to the blood bank");
}
public static void main(String[]args) {
System.out.println("Enter Blood Type(O, A, B, AB)");
System.out.println("Enter rhFactor('+' or '-')");
BloodData bd= new
BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine());
BloodData bd1= new BloodData();
bd.display();
}
}
How can i use the constructor with 2 String parameters? because when I always run the code the first one only run. I'm only a beginner so hope someone could help because I already watched a lot of Youtube vids and I really didn't know why this happens
Java doesn't use named parameters like this for method or constructors. I would be surprised if a video showed such syntax...
new BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine())
You need to define String variables on the line above, then pass them into the constructor. You also shouldn't be combining instance constructors with static variables
class BloodData{
private String bloodType;
private String rhFactor;
public BloodData(String type, String rhFactor) {
this.bloodType = type;
this.rhFactor = rhFactor;
}
...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String x = in.nextLine();
String y = in.nextLine();
BloodData bd = new BloodData(x, y);
}
if you want to call a constructor having two parameters: Use this
BloodData blooddata = new BloodData("A","+");

Can't call method from another class in 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.

How can I set variables from a class of ArrayLists to the Main class?

I have already created an object and tried to set some variables but I cannot find the type of the variables that should I create in order to do not have any problem.
The part of the main class:
Menu menu = new Menu();
scanner.nextLine();
System.out.println("Give a code.");
String code = scanner.nextLine();
menu.setCode(code);
System.out.println("Give a main dish");
String MainDish = scanner.nextLine();
menu.setMainDishes(MainDish);
System.out.println("Give a drink.");
String Drink = scanner.nextLine();
menu.setDrinks(Drink);
System.out.println("Give a sweet.");
String Sweet = scanner.nextLine();
menu.setSweets(Sweet);
And the Menu class:
public class Menu {
ArrayList<String> MainDishes = new ArrayList<>();
ArrayList<String> Drinks = new ArrayList<>();
ArrayList<String> Sweets = new ArrayList<>();
private String code;
public ArrayList<String> getMainDishes() {
return MainDishes;
}
public void setMainDishes(ArrayList<String> mainDishes) {
MainDishes = mainDishes;
}
public ArrayList<String> getDrinks() {
return Drinks;
}
public void setDrinks(ArrayList<String> drinks) {
Drinks = drinks;
}
public ArrayList<String> getSweets() {
return Sweets;
}
public void setSweets(ArrayList<String> sweets) {
Sweets = sweets;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
Compliler give an error because of the String variables that I created.
Your menu class contains ArrayList variables and you try to assign a String to them. Instead of:
menu.setMainDishes(MainDish);
Try:
menu.getMainDishes().add(MainDish);
Also, common convention in Java is to start variables with lowercase, eg mainDish.
You are trying to pass a string when the methods are expecting an ArrayList of strings. If you want to do it the way you currently are, then create an ArrayList, put the user input into it, then pass that ArrayList to the methods that call for it.

How can i access an object from another method in java?

I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.
Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}
While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.
This example:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
Will work, however, it would be better if it was more like this...
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}
You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.
public class SomeClass {
NumberList numberlist; // Definition
....
Then in your create() function just say:
numberlist= new NumberList(length, offset); // Initialization
Declare numberList outside your methods like this:
NumberList numberList;
Then inside create() use this to initialise it:
numberList = new NumberList(length, offset);
This means you can access it from any methods in this class.

How to access object fields in a loop?

I can access the planetName, but not the Surfacematerial,Diameter etc because they are not in the array and in the object. How do I access the objects in a loop and their respective fields?
import java.util.Scanner;
public class Planet {
private String[] planetName;
private String SurfaceMaterial;
private double daysToOrbit;
private double diameter;
public Planet(){
planetName=new String[8];
SurfaceMaterial="";
daysToOrbit=0;
diameter=0;
}
public Planet(String[] planetName, String SurfaceMaterial,double daysToOrbit, double diameter){
this.planetName=planetName;
this.SurfaceMaterial=SurfaceMaterial;
this.daysToOrbit=daysToOrbit;
this.diameter=diameter;
}
public void setPlanetName(){
Scanner in=new Scanner(System.in);
Planet solar[]=new Planet[8];
for(int i=0;i<solar.length;i++){
solar[i]=new Planet(planetName,SurfaceMaterial,daysToOrbit,diameter);
System.out.println("Enter Planet Name::");
planetName[i]=in.next();
System.out.println("Enter Surface Material");
SurfaceMaterial=in.next();
System.out.println("Enter Days to Orbit");
daysToOrbit=in.nextDouble();
System.out.println("Enter Diameter");
diameter=in.nextDouble();
}
for(int i=0;i<solar.length;i++){
System.out.println(planetName[i]);
System.out.println(this.SurfaceMaterial); //This returns only one value that has been entered at the last
}
}
}
public static void main(String[] args) {
Planet planet=new Planet();
Scanner input=new Scanner(System.in);
planet.setPlanetName();
}
}
just access like following
object[index].member ... // or call getter setter
in your case say the first member name is name .. so call like
staff[0].name // this will return BOB
The staff array is declared as local in the Constructor: Or if it is declared in the class context, you are hiding it. So declare the staff array in the class context and then initialize in the constructor:
class Test
{
public Full_time [] Staff;
public Test()
{
Staff = new Full_time [4];
Staff [0] = new Full_time("BoB", 2000, 70000);
Staff [1] = new Full_time("Joe", 1345, 50000);
Staff [2] = new Full_time("Fan", 3000, 80000);
}
}
And then, in the main function:
public static void main(String[] args) {
Tester t = new Tester();
t.staff[i].name = "A Name";
}
However, instead of accessing member field directly it is suggested to use getter or setter function like: getStaff(i) and similar.

Categories