I'm wondering if anyone can give me some pointers on what the next steps in a basic program I have.
I have the following example java code:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
ArrayList<Transport> transportList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void addToList() {
transportList.add(new Transport("Blue", "Large", "Plane"));
transportList.add(new Transport("Red", "Small", "Car"));
transportList.add(new Transport("Brown", "Large", "Train"));
transportList.add(new Transport("Yellow", "Small", "Boat"));
transportList.add(new Transport("Yellow", "Small", "Plane"));
transportList.add(new Transport("Brown", "Large", "Car"));
transportList.add(new Transport("Red", "Large", "Train"));
transportList.add(new Transport("Blue", "Small", "Boat"));
searchColour();
}
public void searchColour() {
System.out.println("Enter a colour to search:\n");
String colourSearch = input.next();
for (Transport transport : transportList) {
if (transport.getColour().toLowerCase().equals(colourSearch.toLowerCase())) {
System.out.printf(
"There is a %s %s that is %s \n",
transport.getSize(),
transport.getType(),
transport.getColour()
);
}
}
searchColour();
}
public static void main(String[] args) {
new Main().addToList();
}
}
public class Transport {
private String colour;
private String size;
private String type;
// All-args constructor, getters and setters omitted for brevity
}
This runs and prompts the user to enter a colour. It then searches the ArrayList and outputs the matches. What I now need to do is to take the results I get from a colour search and reuse them in a menu for selection.
For example if I search for "red", I get:
There is a Small Car that is Red
There is a Large Train that is Red
What I want is to have a number placed in front of them and another prompt to choose which one the person whats. So it should say something like:
- There is a Small Car that is Red
- There is a Large Train that is Red
"Choose which transport you want"
Outputting the next question and prompting for an input with Scanner I can do, I'm not sure how I can add numbers to the start of the results, knowing that as my ArrayList grows the number of items will, and how I do a selection choice from it so a user can press 1 or 2.
Can anyone offer a suggestion? I'm thinking I need to use another ArrayList but I'm not sure how this should be structured.