I am trying to write this method - checkValidBusType() : returns true if entered
ID: 3819210 • Letter: I
Question
I am trying to write this method - checkValidBusType() : returns true if entered bus type is valid and exists in BusType enum and can be converted to a BusType object
Here is the list of Stations
// List of Bus Stations
public enum BusStation {
PHX,
LAX,
LVS,
SAN,
SFO,
YUM;
public static String getBusStationCity(BusStation busStation) {
switch (busStation) {
case PHX:
return "Phoenix";
case LAX:
return "Los Angeles";
case LVS:
return "Las Vegas";
case SAN:
return "San Diego";
case SFO:
return "San Fransisco";
default:
return "Unknown City";
}
}
}
Here is the start of my method
private boolean checkValidBusType() {
return false;
}
This was my initial attempt:
private boolean checkValidBusType(String busStation) {
boolean validBusType = false;
BusStation[] busStationName = BusStation.values();
for(BusStation busStationNames : busStationName)
{
if((sourceStationText.getText() == busStation) && (destStationText.getText() == busStation))
{
validBusType = true;
}
else
{
validBusType = false;
}
}
return validBusType;
}
Explanation / Answer
Hi,
I have provided the class with functions required to validate bus type based on given enum values.
public class Station {
public enum BusStation {
PHX, LAX, LVS, SAN, SFO, YUM;
}
public static String getBusStationCity(BusStation busStation) {
switch (busStation) {
case PHX:
return "Phoenix";
case LAX:
return "Los Angeles";
case LVS:
return "Las Vegas";
case SAN:
return "San Diego";
case SFO:
return "San Fransisco";
default:
return "Unknown City";
}
}
public static boolean checkValidBusType(String busStation) {
boolean validBusType = false;
for (BusStation givenStation : BusStation.values()) {
if (givenStation.toString().equals(busStation)) {
validBusType = true;
}
}
return validBusType;
}
public static void main(String[] args) {
String checkBus="SFO";
//check if bus type is value by passing a string value
System.out.println(checkValidBusType(checkBus));
//Get the name of the city using bus station
System.out.println(getBusStationCity(BusStation.valueOf(checkBus)));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.