来自main的Java类访问

时间:2014-10-22 22:47:34

标签: java class object

public class mainTest {
    public static void main(String[] args) throws Exception {

        Scanner KB = new Scanner(System.in);
        String VehiclesFile = "Vehicles.txt";

        File file1 = new File(VehiclesFile);
        Scanner infile1 = new Scanner(VehiclesFile);
        Vehicle[] Vehicles = new Vehicle[0];

        try {
            Scanner scanner = new Scanner(file1);
            int lineCount = 0;
            while (scanner.hasNextLine()) {
                lineCount++;
                scanner.nextLine();
            }

            Vehicles = new Vehicle[lineCount];

            scanner = new Scanner(file1);
            int VehicleCount = 0;
            while (scanner.hasNextLine()) {
                String[] temp1 = scanner.nextLine().split(",");

                // file has been read into temp1[] now to use Vehicles
                // class type

                Vehicles[VehicleCount] = new Vehicle();
                Vehicles[VehicleCount].setregistration(temp1[0]);
                Vehicles[VehicleCount].setmake(temp1[1]);
                Vehicles[VehicleCount].setModel(temp1[2]);
                Vehicles[VehicleCount].setyear(temp1[3]);
                Vehicles[VehicleCount].setodometer(temp1[4]);
                Vehicles[VehicleCount].setowner(temp1[5]);
                VehicleCount++;

            }
        } catch (IOException e) {
            // Print out the exception that occurred
            System.out.println("Unable to find ");
        }

//*******This is where I need to access the class to print****************
        System.out.println (Vehicle.class.getClasses());

    }
}

我似乎无法理解如何引用类对象的类/数组的特定部分 Vehicle的类定义为get / set,所以我没有包含代码。

3 个答案:

答案 0 :(得分:1)

System.out.println(Arrays.toString(Vehicles));

确保车辆类具有toString()方法覆盖。否则它只会打印出参考文献。

请参阅: How to override toString() properly in Java?

答案 1 :(得分:0)

如果要打印来自Vehicle对象的数据,则必须循环遍历该数组并调用之前提到的getter方法。 它应该像

for(Vehicle v : Vehicles)
{
     System.out.print(v.getYear() + " " + v.getMake() + " " + v.getModel());
}

答案 2 :(得分:0)

对我而言似乎是在混淆类和对象的概念。类是分类的缩写,因此类是一种类型。对象是类的单个实例。所以它是某种类型的单个项目。

您拥有的是一组对象,而不是类,并且您希望打印每个对象的信息。所以说你的阵列中有五辆车,你必须五次调用函数System.out.println(/*data to print*/)。一个用于数组中的每个元素。

要省略重复,可以使用循环:

for (int index = 0; index < Vehicles.length; ++i) {
    System.out.println(Vehicle[index].getMake());
    // do the same to print other attributes of the Vehicle class
}