简体   繁体   中英

Checking Multiple strings with if, else if statement

I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.

import java.util.Scanner;

public class Username

{
public static void main (String[]args)
{

    Scanner kb = new Scanner (System.in);
    String name; 


    System.out.println("Enter your name");
    name = kb.nextLine();
    if (name.equals("barry "))
        System.out.println("you are verified you may use the lift");


    Scanner f = new Scanner(System.in);
    int floor;


    System.out.println("What floor do you want to go to ");
    floor = f.nextInt();

    if (floor >7)
        System.out.println("Invalid entry");
    else if (floor <= 7)
        System.out.println("Entry valid");



    }

    }

Check out this related question:

Test if a string contains any of the strings from an array

Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.

Use the OR symbol "||" or "|".

Such as if (name.equals("barry ") || name.equals("sara"))

For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.

basically, you need an "Or" gate, this would work:

if(name.equals("name1")||name.equals("name2")||name.equals("name3"))

etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM