userInputCar == cars
.... It doesn't work that way, even if you used the String#equals() method to check for proper string equality. If anything it should be something like:
switch (userInputCar.toUpperCase()) {
case "TATA":
System.out.println("You enter TATA as a car name");
break;
case "BMW":
System.out.println("You enter BMW as a car name");
break;
default:
System.out.println("Oops! we are unable to get that name. Thank You:");
}
Notice how userInputCar.toUpperCase()
is used. This allows the User to enter the car name in any letter case an still produce a positive result.
In any case...since the car names are already contained within a String[] Array (cars[]
) you should be checking through the array of names rather than creating a switch/case
mechanism to do this, for example:
// Declare Scanner object as class global:
private final static Scanner sc = new Scanner(System.in);
public static String getCarName() {
String[] cars = {"TATA", "BMW", "Hero", "Honda", "Bajaj", "Yamaha"};
String carName = "";
while (carName.isEmpty()) {
System.out.print("Enter a car name (q to quit): -> ");
carName = sc.nextLine();
// See if 'q' for quit was supplied by User:
if (carName.equalsIgnoreCase("q")) {
return null;
}
// Flag to indicate that supplied car was found within Array:
boolean found = false;
/* Iterate the the cars[] array and see if the User supplied
car exists within that array (ignoring letter case): */
for (String car: cars) {
if (car.equalsIgnoreCase(carName)) {
/* The supplied car name exists. Make the supplied
car name equal the proper car name in array: */
carName = car;
found = true; // Set the `found` flag to true:
break; // Break out of `for` loop:
}
}
// Was the supplied car name found?
if (!found) {
// No...Inform User and have him/her try again...
System.out.println("Oops! We are unable to get that name ("
+ carName + "). Try again..."
+ System.lineSeparator());
carName = ""; // Empty carName to ensure re-loop:
}
}
/* If we get to this point then validation was successfull,
return the car name: */
return carName;
}
To use the above method, you might have something like this:
String car = getCarName();
if (car == null) {
System.out.println("'Quit' Provided!");
return;
}
System.out.println("You entered " + car + " as a car name.");