0

I have my program which reads from a txt file, then turns txt information into a car object and adds them to an arraylist.

try {
     String filePath = "car.txt";
     File f = new File(filePath);
     Scanner sc = new Scanner(f);


     List<Car> car = new ArrayList<Car>();

     while(sc.hasNextLine()){
         String newLine = sc.nextLine();

         String[] details = newLine.split(" ");
         String brand = details[0];
         String model = details[1];
         double cost = Double.parseDouble(details[2]);
         Car c = new Car(brand, model, cost);
         Car.add(c);
     }

However, If a line from the txt file does not contain the three components then it crashes. How would I check if the line contains all 3 components, if not print a message then terminate?

Stack trace -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Main.loadPerson(Main.java:31)
at Main.main(Main.java:12)
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
Buupu
  • 37
  • 1
  • 8

4 Answers4

0

You need to check for the length of details is 3, if not exit as shown below:

     String[] details = newLine.split(" ");
     if(details.length != 3) {
       System.out.println("Incorrect data entered !! Please try again !!! ");
      return;
      } else {
       String brand = details[0];
       String model = details[1];
       double cost = Double.parseDouble(details[2]);
       Car c = new Car(brand, model, cost);
       Car.add(c);
     }
developer
  • 19,553
  • 8
  • 40
  • 57
0

You can check the length of return array from split by:

int count = details.length;

and then decide what to do

Pooya
  • 5,593
  • 3
  • 19
  • 41
0

check length before accessing elements,

try the pattern \\s+ to avoid trimming spaces, there is a typo in your code where adding Car to car list

    while (sc.hasNextLine()) {
        String newLine = sc.nextLine();
        String[] details = newLine.split("\\s+");
        if (details.length == 3) {
            String brand = details[0];
            String model = details[1];
            double cost = Double.parseDouble(details[2]);
            Car c = new Car(brand, model, cost);
            car.add(c);
        } else {
            System.out.println("Invalid input");
        }
    }
Saravana
  • 11,085
  • 2
  • 29
  • 43
0

If the file doesn't contain the 3 components, then details will be empty. use this instead.

if(details.length() != 3){
    System.out.println("Invalid .txt file!");
    break;
}
ItamarG3
  • 3,846
  • 6
  • 28
  • 42