Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing string and integer arrays against user input

I have created arrays for strings and integers I want to use in my program and I want to use them instead of using

(name.equals "barry"||"matty"

for example.

I want to know how to write the if statement to check the user input against the strings in the array.

import java.util.Scanner;

public class Username
{
    public static void main (String[]args)
    {
        Scanner kb = new Scanner (System.in);
        // array containing usernames 
        String [] name = {"barry", "matty", "olly","joey"}; 

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

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

        int [] floor = {0,1,2,3,4,5,6,7};

        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");
    }
}
like image 221
user3151959 Avatar asked Feb 14 '23 09:02

user3151959


1 Answers

I think you're just looking for List.contains - but that requires a List rather than an array, of course. There are two obvious options here.

Firstly, you could use a List<String> to start with:

List<String> names = new ArrayList<>();
names.add("barry");
names.add("matty");
names.add("olly");
names.add("joey");
...
if (names.contains(name))
{
    ...
}

Alternatively, you could use Arrays.asList to create a view:

String[] names = {"barry", "matty", "olly", "joey"}; 
List<String> namesList = Arrays.asList(names);
...
if (namesList.contains(name))
{
}

As a third option, if you put make your names array sorted (either by hand or by calling Arrays.sort) you could use Arrays.binarySearch to try to find the name entered by the user:

String[] names = {"barry", "matty", "olly", "joey"}; 
Arrays.sort(names);
...
if (Arrays.binarySearch(names, name) >= 0)
{
    ...
}
like image 110
Jon Skeet Avatar answered Mar 05 '23 21:03

Jon Skeet