Search code examples
javaobjectarraylistdynamic-arrays

How to use input to create an object


I have a CarModel class that has three fields: name, fuelEconomy, and gasTankSize.

class CarModel {
    private String name;
    private double fuelEconomy;
    private double gasTankSize;

    CarModel(String name, double fuelEconomy, double gasTankSize) {
        this.name = name;
        this.fuelEconomy = fuelEconomy;
        this.gasTankSize = gasTankSize;
    }

    String getName() {
        return name;
    }

    double getFuelEconomy() {
        return fuelEconomy;
    }

    double getGasTankSize() {
        return gasTankSize;
    }
}

Given the input as a string of text separated by a new line:

MODEL Camry 6.5 58 
MODEL Civic 7.5 52
FINISH

How can I create a new object every time the word MODEL is in the input, store the model in an array, use the following words as the data for those fields and end the program when FINISH is in the input?


Solution

  • Inside main method, try doing something like this (Using try with resources):

    public static void main(String args[]){
    String line;
    List<CarModel> cars = new ArrayList<>();
      try(Scanner sc = new Scanner(System.in)){
         while(sc.hasNextLine()){
         line = sc.nextLine();
         String[] arr = line.split(" ");
         if(arr[0].equalsIgnoreCase("Model")){
            cars.add(new CarModel(arr[0], Double.parseDouble(arr[1]), Double.parseDouble(arr[2])));
          }else if(arr[0].equalsIgnoreCase("Finish"){
            break;
          }
        }
       }catch(ArrayIndexOutOfBoundsException ex){
         // do something here! 
       }catch(Exception ex){
         // do something here as well!
       }    
    }