Home > OS >  Select object via scanner and add it to an arrayList
Select object via scanner and add it to an arrayList

Time:09-21

so I want to add an already created object to a list selecting it from the console (i dunno if a Scanner works).

Scanner input = new Scanner(System.in);

    Car c1 = new Car("bmw", 1);
    Car c2 = new Car("mercedes", 1);
    Car c3 = new Car("susuki", 1);

    ArrayList<Car> carList = new ArrayList<>();
    carList.add(c1);
    carList.add(c2);

    //something like this
    Car carToAdd = input.nextCar();
    carList.add(carToAdd);

for example I want to add the Car c3 to the ArrayList. please help and thank you D:

CodePudding user response:

Depending on how you want to display options, and what you want the user to input to the console, you may want to handle different scenarios. The easiest way I can think of is to list all cars available in one Array, and then listen for an index (offset by one, if you'd like). Then use that index to pull the desired car out of the cars Array, and put it into your result Array.

Here's an example. Instead of creating a car class, I just used Strings for simplicity.

import java.util.Scanner; 
import java.util.ArrayList;
class Main {
    public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       ArrayList<String> cars = new ArrayList<String>();
       cars.add("chevy");
       cars.add("ford");
       cars.add("weiner-mobile");
       System.out.println("Please select a car");
       for(int i = 0; i<cars.size(); i  ){
           System.out.println(String.valueOf(i 1) " ) "   cars.get(i));
       }
       int reply = scanner.nextInt();
       System.out.println("you chose: "   cars.get(reply-1));
       ArrayList<String> chosenCar = new ArrayList<String>();
       chosenCar.add(cars.get(reply-1));

    }
}

Output:

Please select a car
1 ) chevy
2 ) ford
3 ) weiner-mobile
> 2
you chose: ford

note: you probably want to make sure the input is an index in range, either by surrounding it in a try/catch and handling the indexOutOfRange exception, or checking the index against the length of the Array to ensure it's within range before calling get(i). The nextInt() call will throw an exception if the input is not castable to an int

  • Related