Ваш код действительно не имеет большого смысла.Исходя из того, что я понимаю в описании вашей проблемы, приведенный ниже код может или не может быть тем, что вы хотите сделать:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class VehicleList {
public class Vehicle {
private final String brand;
private final String make;
private final String year;
public Vehicle(String[] args) {
if (args.length < 3) {
throw new IllegalArgumentException("Too few args: " + args.length);
}
this.brand = args[0];
this.make = args[1];
this.year = args[2];
}
@Override
public String toString() {
return String.format("%s %s %s", year, brand, make);
}
}
public List<Vehicle> readVehicles(String fileName) throws IOException {
List<Vehicle> vehicles = new ArrayList<Vehicle>();
System.out.println(String.format("Reading vehicles from %s:", fileName));
readVehicles(vehicles, new Scanner(new File(fileName)), false);
System.out.println(String.format("Reading vehicles from user:"));
readVehicles(vehicles, new Scanner(System.in), true);
return vehicles;
}
private void readVehicles(List<Vehicle> vehicles, Scanner scanner, boolean skipLineCheck) {
int count = 0;
while (skipLineCheck || scanner.hasNextLine()) {
String[] tokens = scanner.nextLine().split("\\s+");
if (tokens.length < 3) {
break;
}
vehicles.add(new Vehicle(tokens));
count++;
}
scanner.close();
System.out.println(String.format("Read %s vehicles", count));
}
public static void main(String[] args) throws IOException {
VehicleList instance = new VehicleList();
List<Vehicle> vehicles = instance.readVehicles("vehicles.txt");
System.out.println("Read the following vehicles:");
System.out.println(Arrays.toString(vehicles.toArray()));
}
}
Логический skipLineCheck необходим, чтобы сканер не мог прочитать последнюю строку в файлебросая NoSuchElementException.Для пользовательского ввода мы не хотим делать эту проверку, потому что он заставляет пользователя давать дополнительный RETURN, чтобы завершить ввод.
Чтобы запустить это, вам нужно создать файл с именем «Vehicles.txt» вваш рабочий каталог, например, со следующим содержимым:
Volvo Station 2008
Audi A4 2009
Honda Civic 2009
Toyota Prius 2008
Тестовый прогон дает вывод, как показано ниже:
Reading vehicles from vehicles.txt
Read 4 vehicles
Reading vehicles from user
Nissan Micra 2002
BMW cabriolet 1996
Read 2 vehicles
Read the following vehicles:
[2008 Volvo Station, 2009 Audi A4, 2009 Honda Civic, 2008 Toyota Prius, 2002 Nissan Micra, 1996 BMW cabriolet]