My program works if I initialize my Enum Cities as null but I want it to be Optional. I can make it Optional but then the class Address which is supposed to take Cities as one of it's parameters won't do so because Cities is not defined as Optional in the class Address but I can't change it so that the Optional is the parameter of this class and that it works
This is my enum class
public enum Cities {
NEWYORK("New York",10000),
LOSANGELES("Los Angeles",90000),
CHICAGO("Chicago",60000),
NEWORELANS("NEW Orlans",70000),
DALLAS("Dallas",75000);
private final String name;
private final Integer postalCode;
Cities(String name, Integer postalCode) {
this.name=name;
this.postalCode=postalCode;
}
It works like this
private static Address addressInput (Scanner scanner) {
ArrayList<Cities> cityList = new ArrayList<>();
Cities city = null;
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = cityList.get(j);
}
}
if (city == null) {
System.out.println("Please select one of the cities on the list.");
}
} while (city == null);
String street = dataInput(scanner, "Name of the street: ");
String houseNumber = dataInput(scanner, "House number: ");
return new Address.Builder(city)
.atStreet(street)
.atHouseNumber(houseNumber)
.build();
}
But Adress constructor now won't accept city if it's Optional because it is defined differently in Adress class
private static Address addressInput (Scanner scanner) {
ArrayList<Cities> cityList = new ArrayList<>();
Optional<Cities> city = Optional.empty();
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Unesite naziv jednog od ponuđenih gradova: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = Optional.ofNullable(cityList.get(j));
}
}
if (city.isEmpty()) {
System.out.println("Molimo odabrati jedan od ponuđenih gradova.");
}
} while (city.isEmpty());
public class Address {
private String street;
private String houseNumber;
private Cities city;
public Address(Cities city,String street, String houseNumber) {
this.street = street;
this.houseNumber = houseNumber;
this.city=city;
}
public static class Builder {
Cities city;
String street;
String houseNumber;
public Builder (Cities city){
this.city=city;
}
public Builder atStreet (String street){
this.street=street;
return this;
}
public Builder atHouseNumber (String houseNumber){
this.houseNumber=houseNumber;
return this;
}
public Address build (){
Address address = new Address();
address.city=city;
address.houseNumber=houseNumber;
address.street=street;
return address;
}
}
How to edit class to accept Optional?