I have created an array with flight destinations in the public class flights and now I want to print out the array using a method in the public class customers. But for some reason the array always prints out as null and I sandly can't my mistake.
main class:
public class Main {
public static void main(String[] args) {
flight flight = new flight();
customer customer = new customer();
flight.createExampleData();
customer.output();
}
}
public class flights:
public class flight{
public String[] destination = new String[2000];
public void createExampleData(){
this.destination[1] = "Paris";
this.destination[2] = "Geneve";
this.destination[3] = "Florida";
}
}
public class customers:
public class customer{
flight flight = new flight();
public int i;
public void output() {
this.i=1;
while (i<4){
System.out.println("Flightnumber: " + this.i);
System.out.println("Destination: " + flight.destination[this.i]);
System.out.println("");
this.i++;
}
}
}
(I can't put the print in the flights class for reasons not visible in this simplyfied version of the program)
Outcome from the method outpout after the method createExampleData:
Flightnumber: 1
Destination: null
Flightnumber: 2
Destination: null
Flightnumber: 3
Destination: null
Thanks for the help
Maybe you haven't executed the function createExampleData() in your customers class?
You are using two different flight objects, one created in main and one created in your customer class and then you call flight.createExampleData on the instance created in main but the output method uses the one in the customer object so the array in that one was never given any values, hence null in the output.
My suggestion for now is to make the flight variable in customer public
public class customer{
public flight flight = new flight();
...
}
and then change main to
public class Main {
public static void main(String[] args) {
customer customer = new customer();
customer.flight.createExampleData();
customer.output();
}
}
A better solution could be to add a getFlight() method to customer instead and keep the variable private.
flight.createExampleData();
When you call this, createExampleData method in Flight class is executed.
customer.output();
When you call this output method in Customer class is executed.
There is no relationship between Flight and Customer class in your code. So, customer object's output method wouldn't know what happened in the createExampleData of Flight class.
You can rather do this
String [] flightDestinations = flight.createExampleData();
customer.output(flightDestinations);
You will have to change your output method in customer class to use this string array and print its details. Also, the return type for createExampleData should be String [] for this to work.
Related
I am trying to create a parent class for cars and subclasses from it. Each one has separate methods and store them in an array then if the class are subclass try to call the method on it.
Parent class
public class car {
public String name ;
public double price ;
public car (String name , int price) {
this.name = name ;
this.price = price;
}
public String toString() {
return "car name : "+this.name
+" Price : " +this.price ;
}
}
Sub class
public class CarMotors extends car {
public float MotorsCapacity ;
public CarMotors( String name, int price , float MotorsCapacity) {
super(name, price);
this.MotorsCapacity = MotorsCapacity ;
}
public float getMotorsCapacity() {
return this.MotorsCapacity;
}
}
Main class
public class Test {
public static void main(String[] args) {
car [] cars = new car[2] ;
cars[0] = new car("M3" , 78000);
cars[1] = new CarMotors("M4" , 98000 , 3.0f);
for(int i=0 ;i<2;i++){
if(cars[i] instanceof CarMotors) {
System.out.println(cars[i].getMotorsCapacity()); // error here
}else {
System.out.println(cars[i].toString());
}
}
}
}
As you can see, I can't print the getMotorsCapacity(). I am new to Java. I think there is a cast that need to happen, but I don't now how.
Being short... a class only can see what its yours behaviors.
In your example CarMotors is a Car, that's fine.
But the behavior getMotorsCapacity() is created in CarMotors and it wasn't in Car.
That error occurs because, it's OK in a variable Car you are able to put an instance of CarMotors because CarMotors is a Car. So, any method that is in Car is also in CarMotors, yes, you can call. Look at cars[i].toString() there's no problem here.
You need explicitly say to compiler:
"- oh, right, originally this variable is a Car, but I know that is a CarMotors inside that. I will make a cast here, OK compiler? Thanks."
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
Or, to be more clear:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());
I want to use the object person in the Librarian_Interface class, but this call the method login() in a loop. I think there is something I don't understand with java instance and I tried to get person with a constructor or methode but in vain. Thanks !
public class Login_Interface {
Person person;
public Login_Interface() {
db.initConnection();
person = login(db, in);
if (person != null)
{
Librarian_Interface a = new Librarian_Interface();
a.run();
}
}
public void run() {
}
public static Person login(DbConnection db, Scanner sc) {
Persons.setDbConnection(db);
Persons persons = Persons.getInstance();
System.out.print("\nEnter your Phone Number : ");
String phone = sc.nextLine();
System.out.print("\nEnter your Password : ");
String password = sc.nextLine();
return persons.login(phone, password);
}
}
public class Librarian_Interface {
public Librarian_Interface() {
// What I want
// System.out.print(person); or person.getAge(); ...
All you have to do is pass the person object to the Librarian_Interface constructor. then you can call methods getAge on it, etc.
public class Librarian implements Runnable {
private final Person person;
public Librarian(Person person) {
this.person = person;
}
#Override
public void run() {
int age = person.age();
// ... whatever else
}
}
By the way, the convention in Java is to use upper camel case for class names, with no underscores. So it would be better to name the class LibrarianInterface. Also, it's probably not the best idea to call it LibrarianInterface if it is in fact a class and not an interface.
Since Librarian has a public run method, it's a good idea to have it implement Runnable so that users of the class see how it is meant to be used.
I have a method to issue a parkingTicket in my officer class,
public ParkingTicket issueParkingTicket(ParkedCar car,ParkingMeter meter){
if(isParkingTimeExpired(car,meter) == true){
ParkingTicket ticket = new ParkingTicket(officerName,officerBadgeNumber,car.getLicensePlateNumber(),calculateFine(car,meter));
ticket.displayDetails();
return ticket;
} else
{ return null;
}
}
I was asked to modify it in a way to have it not return anything so i made it void, so I did it this way
public void issueParkingTicket(ParkedCar car,ParkingMeter meter){
if(isParkingTimeExpired(car,meter) == true){
ParkingTicket ticket = new ParkingTicket(officerName,officerBadgeNumber,car.getLicensePlateNumber(),calculateFine(car,meter));
ticketList.add(ticket);
ticket.displayDetails();
}
Now in my main driver class, I have to created an officer object but since I had to make the method void to not return anything I am getting an error saying void cannot be converted to ParkingTicket, if i take away myCar1,myMeter1 from the parentheses, I get an error telling me there's arguments required ParkedCar , ParkingMeter. How can I make it so I don't get an error and the officer object created can issue a parking ticket?
public class Driver
{
main method
public static void main(String [] args){
ParkedCar myCar1 = new ParkedCar("Fred","toyota",2013,"Z1234",25);
myCar1.displayDetails();
ParkingMeter myMeter1 = new ParkingMeter("SYDNEY",true,0.15,70);
myMeter1.displayDetails();
PoliceOfficer officer1 = new PoliceOfficer("John doe","DMX1234");
ParkingTicket ticket = officer1.issueParkingTicket(myCar1,myMeter1);
This is the source of my error ParkingTicket ticket = officer1.issueParkingTicket(myCar1,myMeter1);
You can just remove the part that says:
ParkingTicket ticket =
in your main method.
Since the ticket is created in the function there is no need to create a new ticket when you call the function.
Add an array or List to ParkedCar that keeps track of all the tickets for that vehicle.
public void issueParkingTicket(ParkedCar car, ParikingMeter meter)
{
if(isParkingTimeExpired(car,meter) == true){
ParkingTicket ticket = new ParkingTicket(officerName,officerBadgeNumber,car.getLicensePlateNumber(),calculateFine(car,meter));
car.tickets.add(theTicket);
}
then in your main class you can access every ticket for any car object.
public static void main(String [] args)
{
ParkedCar car = new ParkedCar(/*params*/);
Officer officer1 = new Officer(/*params*/);
officer1.issueTicket(/*params*/);
//make a getter for the tickets in the ParkedCar class
car.getTickets();
}
You can pass in a ticket, and manipulate the ticket inside the issueParkingTicket method.
ParkingTicket ticket = new ParkingTicket();
officer1.issueParkingTicket(myCar1,myMeter1,ticket);
ticket.displayDetails();
So I have a List of Actors and I want to get each Actors dynamic class name.
For example here is my Actor list: People, Birds, Cows.
I want to get as result the same: "People, Birds, Cows" but without a name attribute in the Actors class. Is it possible?
Example code (here instead of list I used array) :
public Area map[][];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getName(); //this results "Area" instead of AntHillArea
Edit: There was other problems with the code, getClass().getName() works fine. Thanks anyway.
String className = obj.getClass().getSimpleName();
Update:
public class Test {
public static void main(String[] args) {
Area map[][] = new Area[1][1];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getSimpleName(); // returns "AntHillArea"
System.out.println(name);
}
}
class Area {
}
class AntHillArea extends Area {
}
Use getSimpleName method. It gives you only class and will remove any package if having.
You can do this:
class Dog
{
//code
public String getName()
{
return Dog.class.getName();
}
//better
#Override
public String toString()
{
return Dog.class.getName();
}
}
And similarly for each class. Or have a global one as mentioned in other answers as:
public static String getClassName(Class<?> clas){
return clas.getName();
}
To use Dog dog = new Dog(); getClassName(dog.class);
I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?
First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?