【问题标题】:Reading vehicles from a text file line by line and passing those vehicles into a constructor in Java从文本文件中逐行读取车辆并将这些车辆传递给 Java 中的构造函数
【发布时间】:2017-02-25 05:37:54
【问题描述】:

我是 Java 新手,我的任务是逐行从文本文件中读取车辆,然后停在特定车辆上,例如(车辆、汽车、卡车、自行车、美国汽车和外国汽车)乘车在这些车辆之后并将它们传递给一个构造以将车辆转换为对象,这样我就可以将这些对象放入一个数组中。车辆将彼此扩展,并以文本文件中的特定布局进行扩展。我在想办法将这些行传递给构造函数并从构造函数返回对象时遇到了麻烦。这是文本文件布局的示例。

vehicle
owner's name (string)
address (string)
phone (string)
email (string)

car - extends of vehicle 
owner's name (string)
address (string)
phone (string)
email (string)
true or false for convertible (boolean)
color (string)

american car - extends of car
owner's name (string)
address (string)
phone (string)
email (string)
true or false for convertible (boolean)
color (string)
true or false for made in Detroit (boolean)
true or false for union shop (boolean)

foreign car - extends of car
owner's name (string)
address (string)
phone (string)
email  (string)
true or false for convertible (boolean)
color (string)
country of manufacturer (string)
import duty (float)

bicycle - extends of vehicle 
owner's name (string)
address (string)
phone (string)
email (string)
number of speeds (int)

truck - extends of vehicle 
owner's name (string)
address (string)
phone (string)
email (string) 
number of tons (float)
cost of truck (float)
date purchased (format below in example)

另外,这是我使用的示例数据:

foreign car
aMarioy
Mario's house
(777) 777-7777
gmario@mario.com
false
black
Italy
4415.91

truck
aDougy
Doug's house
(123) 456-7890
hdoug@doug.com
30
61234.56
8/10/2003

vehicle
aRobby
Rob's house
(987) 654-3210
irob@rob.com

bicycle
bTommy
Tom's house
(246) 810-1214
jtom@tom.com
7

truck
bGeorge
George's house
(666) 666-6666
kgeorge@george.com
25
51234.56
12/4/2004

vehicle
bTim
Tim's house
(111) 111-1111
tim@tim.com

bicycle
bJim
Jim's house
(555) 555-5555
Ajim@jim.com
5

american car
bJohn
John's house
(888) 888-8888
Bjohn@john.com
true
green
false
true

car
cKen
Ken's house
(999) 999-9999
Cken@ken.com
false
orange

foreign car
cMario
Mario's house
(777) 777-7777
Dmario@mario.com
false
black
Italy
4415.91

truck
zDoug
Doug's house
(123) 456-7890
Edoug@doug.com
30
61234.56
8/10/2003

vehicle
eRob
Rob's house
(987) 654-3210
Frob@rob.com

bicycle
fTom
Tom's house
(246) 810-1214
Gtom@tom.com
7

american car
gSam
Sam's house
(333) 333-3333
Hsam@sam.com
false
blue
true
false

这是我的代码...

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

public class test4{
   public static void main(String[] args)throws FileNotFoundException {
      try{
         Scanner file = new Scanner(new File(args[0]));
         //ArrayList<Vehicle> vehicleList = new ArrayList<>();
         String line = new String();
         String newLine = new String();
         ArrayList<String> s1List = new ArrayList<>();
         ArrayList<String> s2List = new ArrayList<>();
         ArrayList<String> s3List = new ArrayList<>();
         ArrayList<String> s4List = new ArrayList<>();
         ArrayList<String> s5List = new ArrayList<>();
         ArrayList<String> s6List = new ArrayList<>();

         while(file.hasNextLine()){
            line = file.nextLine();
            if(line.equals("vehicle")){
              while(file.hasNextLine()){
               newLine = file.nextLine();
               if(!(newLine.equals(""))){
               s1List.add(newLine);
               }
               if(newLine.equals("")){
                  break;
               }
              }
            }
            if(line.equals("truck")){
              while(file.hasNextLine()){
               newLine = file.nextLine();
               s2List.add(newLine);
               if(newLine.equals("")){
                  break;
               }
              }
            }
            if(line.equals("bicycle")){
              while(file.hasNextLine()){
               newLine = file.nextLine();
               s3List.add(newLine);
               if(newLine.equals("")){
                  break;
               }
              }
            }
            if(line.equals("car")){
              while(file.hasNextLine()){
               newLine = file.nextLine();
               s4List.add(newLine);
               if(newLine.equals("")){
                  break;
               }
              }
            }
            if(line.equals("american car")){
              while(file.hasNextLine()){
               newLine = file.nextLine();
               s5List.add(newLine);
               if(newLine.equals("")){
                  break;
               }
              }
            }
            if(line.equals("foreign car")){
              while(true){
               newLine = file.nextLine();
               s6List.add(newLine);
               if(newLine.equals("")){
                  break;
               }
              }
            }                                                            
         }
         /*
         String[] s1 = s1List.toArray(new String[0]);
         String[] s2 = s2List.toArray(new String[0]);
         String[] s3 = s3List.toArray(new String[0]);
         String[] s4 = s4List.toArray(new String[0]);
         String[] s5 = s5List.toArray(new String[0]);
         String[] s6 = s6List.toArray(new String[0]);
         */

         /*
         System.out.println(s1.length);


         for(String a: s1){
            System.out.println(a);
         }
         */


         /*
         for(String a: s1List){
            System.out.println(a);
         }
         for(String a: s2List){
            System.out.println(a);
         }
         for(String a: s3List){
            System.out.println(a);
         }
         for(String a: s4List){
            System.out.println(a);
         }
         for(String a: s5List){
            System.out.println(a);
         }
         for(String a: s6List){
            System.out.println(a);
         }
         */



      }catch(FileNotFoundException ex){
         System.out.println("File not found.");
      }
   }
   public boolean equals(Object o){
      if(this == o){
         return true;  
      }
      if(o == null){
         return false;
      }
      return false;
   }   
}


class Vehicle{
   private String owner = new String();
   private String address = new String();
   private String phone = new String();
   private String email = new String();

   public Vehicle(String[] strArr){
      owner = strArr[0];
      address = strArr[1];
      phone = strArr[2];
      email = strArr[3];
   }
}

我目前让程序扫描文本文件中的车辆,然后将顺序行存储到一个在空行处停止的数组列表中。我不确定如何将特定索引从数组列表传递给构造函数,因为我在想,因为车辆总是处于特定布局但顺序不同。我可以计算数组列表中的索引,以确定我可以传递给构造函数的内容。

感谢您的帮助。

【问题讨论】:

    标签: java arrays string object constructor


    【解决方案1】:

    您可以将输入文件转换为 CSV 吗?会更容易阅读和解析...

    https://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

    然后您可以简单地读取一行并将该车辆/汽车/卡车/任何您需要传递给构造函数的所有数据。

    编辑 如果没有,我会做一些接近以下的事情。注意 - 这是在 C# 中,但同样可以在 Java 中完成。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace VehicleParsing
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Will maintain the string in the current line
                string line;
    
                // Contains the vehicles
                List<Vehicle> vehicles = new List<Vehicle>();
    
                // Contains all properties associated with the current vehicle being looked at
                List<string> currentVehicleData = new List<string>();
    
                // Read the file and display it line by line.
                System.IO.StreamReader file = new System.IO.StreamReader("C:/Users/Timot/Desktop/vehiclesample.txt");
                while ((line = file.ReadLine()) != null)
                {
                    // Indicates we have read in all properties of the current vehicle
                    if(String.IsNullOrEmpty(line))
                    {
                        string vehicleType = currentVehicleData[0];
                        switch (vehicleType)
                        {
                            case "foreign car":
                                vehicles.Add(new ForeignCar(currentVehicleData));
                                break;
                            case "truck":
                                vehicles.Add(new Truck(currentVehicleData));
                                break;
                            case "vehicle":
                                vehicles.Add(new Vehicle(currentVehicleData));
                                break;
                            case "bicycle":
                                vehicles.Add(new Bicycle(currentVehicleData));
                                break;
                            case "american car":
                                vehicles.Add(new AmericanCar(currentVehicleData));
                                break;
                            case "car":
                                vehicles.Add(new Car(currentVehicleData));
                                break;
                            default:
                                throw new NotImplementedException();
                        }
    
                        currentVehicleData = new List<string>();
                    }
    
                    // Indicates the current vehicle's data is still being read
                    else
                    {
                        currentVehicleData.Add(line);
                    }
                }
    
                file.Close();
            }
        }
    }
    

    在 Java 中:

    package com.company;
    
    import sun.reflect.generics.reflectiveObjects.NotImplementedException;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            // Holds the list of all vehicles found in the file
            ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>();
    
            // Holds the data associated with the current vehicle being read
            ArrayList<String> currentVehicleData = new ArrayList<String>();
    
            // Java knowledge lacking here - not certain why I can't simply let the FNF exception bubble up
            Scanner file = null;
            try {
                file = new Scanner(new File("C:/Users/Timot/Desktop/vehiclesample.txt"));
            } catch(FileNotFoundException fnfe) {
                // Do something with this exception
                return;
            }
    
            String line;
            while(file.hasNextLine()) {
                // Get next line
                line = file.nextLine();
    
                // Next line is empty, so currentVehicleData has all the data associated the current vehicle
                if(line.isEmpty()) {
                    vehicles.add(GetVehicle(currentVehicleData));
                    currentVehicleData = new ArrayList<String>();
                }
    
                // Still reading data for the current vehicle
                else {
                    currentVehicleData.add(line);
                }
            }
    
            // Add final vehicle
            vehicles.add(GetVehicle(currentVehicleData));
    
            file.close();
        }
    
        public static Vehicle GetVehicle(ArrayList<String> properties)
        {
            String vehicleType = properties.get(0);
            switch(vehicleType) {
                case "foreign car":
                    return new ForeignCar(properties);
                case "truck":
                     return new Truck(properties);
                case "vehicle":
                     return new Vehicle(properties);
                case "bicycle":
                     return new Bicycle(properties);
                case "american car":
                     return new AmericanCar(properties);
                case "car":
                     return new Car(properties);
                default:
                    throw new NotImplementedException();
            }
        }
    }
    

    【讨论】:

    • 你好。我不明白你的 if(String.IsNullOrEmpty(line)) 语句的逻辑。该语句不会在大多数情况下返回 false 而不是在内部运行 switch 吗?
    • 每当在文本文件中找到一个空行时,if 语句的计算结果为 true,这也是定义新车辆的时候。然而,在那之前,该空行之前的所有内容都构成了单个车辆的属性。所以我正在做的就是收集列表中的所有这些属性,当下一行为空时,我创建一个新的车辆对象并清空属性列表,以便它可以收集下一辆车的属性
    • 你好。由于您正在检查空间以了解车辆属性何时结束,我如何检查空间和文件结尾?这样做的原因是,如果文本文件没有以空格结尾,它不会将最后一辆车传递给构造函数。
    • if(line.equals("")|!(line.equals("")))
    • 嗯,我不确定我是否跟随。 while 循环在 EoF 退出,因此您无需检查。我不确定你的 if 语句是否正确,你会想要 if(line.trim().equals(""))。
    【解决方案2】:

    从文本文件中读取信息时使用 switch 语句。这会让事情变得更容易!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 2021-11-05
      • 2018-05-06
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多