0

The pitch of the code shows an error!

public static void switchTest() {
    String[] cars = {"TATA", "BMW", "Hero", "Honda", "Bajaj", "Yamaha"};

    System.out.println("Enter a car name:");
    Scanner sc = new Scanner(System.in);
    String userInputCar = sc.nextLine();

    switch (userInputCar == cars) {
        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("Ops! we are unable to get that name. Thank You:)");
    }
}

Let me ask this question in the proper way, We are going to compare user input with The given array. So now the question is how can we do this?

  • [How do I compare strings in Java?](https://stackoverflow.com/q/513832) – Pshemo Mar 11 '23 at 08:19
  • 1
    You should review a tutorial on `switch` statements. – tgdavies Mar 11 '23 at 09:01
  • 1
    `userInputCar` is a `String`, while `cars` is `String[]`, those can never be the same. Maybe you meant to use `switch (userInputCar)`? Otherwise, you really need to be better explain what you're trying to do. Maybe you meant `Arrays.asList(cars).contains(userInputCar)`? However, then your use of `switch` makes no sense. – Mark Rotteveel Mar 11 '23 at 11:23
  • Hello. To update your question use [edit] option. Consider using it to clarify what you mean by "*..compare user input with The given array*" (mentioned in one of your comments). Note that single String object *can't be compared to array* since array *is not a String itself*. It is like attempting to comparing Human to House (single House can *contain* many Humans, but is not Human itself). Maybe you wanted to ask about checking "if array *contains* a String?". – Pshemo Mar 12 '23 at 15:19

5 Answers5

1

A switch is like having a lot of "if .. " commands.

So the comparison isn't in the switch:

switch (userInputCar == cars)

but in the case

switch (userInputCar) { // Value to check

    case "TATA":   // if "TATA".equals(userInputCar)
        break;

    case "BMW":   // else if "BMW".equals(userInputCar)
        break;

    default:      // else
}

To check against the list:

if(Arrays.asList(cars).contains(userInputCar)) {
   // Found
} else {
   // Not found
}
Bill Mair
  • 1,073
  • 6
  • 15
  • I think I am unable to ask this question correctly! Let me ask this question in the proper way, We are going to compare user input with The given array. So now the question is how can we do this? – DIPTENU SARKAR Mar 11 '23 at 09:13
  • Added how to use Arrays to compare the contents of your list. – Bill Mair Mar 11 '23 at 09:24
1

I think you need to do this :

public static void switchTest() {
    switch ( userInputCar ) {
        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("Ops! we are unable to get that name. Thank You:)");
    }
}
0

If you want to try to check user input with an array you can check the below code

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
     String[] cars = {"TATA", "BMW", "Hero", "Honda", "Bajaj", "Yamaha"};
     boolean check=true;
    System.out.println("Enter a car name:");
    Scanner sc = new Scanner(System.in);
    String userInputCar = sc.nextLine();
    
    
    for(int i=0;i<cars.length;i++)
    {
        if(cars[i].equals(userInputCar))
        {
             System.out.println("You enter "+ cars[i] +" as a car name");
             check=false;
        }
      
    }
    
       if(check)
        {
          System.out.println("Ops! we are unable to get that name. Thank You");
        }
    
    }
    
    
    /*
       Here is the Output
       
       Enter a car name:
       Hero
       You enter Hero as a car name




    */
}
0

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.");
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
0

You no cannot compare a entire array with the single variable but you can compare a each and element of an array with the user input value...

Scanner scanner = new Scanner(System.in);
String[] cars  = {"TATA", "BMW", "AMBASSADOR", "MARUTI"};
String input = scanner.nextLine();
int flag = 0;
for(String tempcar : car) {
if(tempcar == input.toUpperCase())
    flag = 1;
}
if(flag == 1)
    System.out.println("car founded in the list");
else
   System.out.println("oops! No such in the list");