0

I have multiple classes of the same package and need to access some variables in different classes. How would I access carName from MenuDisplay in the Car class? feels like I'm almost there but just can't figure it out. Thanks

package carrentaltester;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MenuDisplay {

    public static void displayCarList() {

        String CSVfileName = "CarList.csv";
        int counter = 0;
        try { //open and read the CSV file
            File file = new File(CSVfileName);
            Scanner input = new Scanner(file);
            System.out.format("%-8s%-18s%-10s%-16s%-16s%-16s\n",
                    "Car No.", "Car Name", "Seats", "Transmission", "Car Type",
                    "Rate/Day($");
            System.out.format("%-8s%-18s%-10s%-16s%-16s%-16s\n", "-------",
                    "-------", "----- ", "------------", "---------",
                    "--------");
            while (input.hasNextLine()) {
                String line = input.nextLine();
                counter++;
                String fields[] = line.split(",");
                String carNumber = fields[0];
                String carName = fields[1];
                String seats = fields[2];
                String transmission = fields[3];
                String carType = fields[4];
                String ratePerDay = fields[5];

                System.out.format("%-8s%-18s%-10s%-16s%-16s%-16s\n",
                        carNumber, carName, seats, transmission, carType,
                        ratePerDay);
            }
package carrentaltester;


public class Car {
    
    double carRate;
    String carName; 
        
    MenuDisplay carInfo = new MenuDisplay();
    
}

2 Answers 2

2

The carName is a field variable of a Car object. You must instantiate a Car at first, and then access its carName field.

Car car = new Car();

(...)

car.carName = fields[1];

Where you should instantiate a Car object depends on the situation. I would pass it as an argument to displayCarList.

public static void displayCarList(Car car) {
    (...)
    car.carName = fields[1];
    (...)
}

Usage:

public class Car {
    double carRate;
    String carName;

    public static void main(String[] args) {
        Car car = new Car();
        MenuDisplay carInfo = new MenuDisplay(car);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Create an object of Car class and set values. Then you can access.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.