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");
}
}
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)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With