How to accept multiple username and password using the following code? if (value1.equals("username") && value2.equals("password"))
4 Answers
Perhaps you're just after a simple loop like this:
String[][] userPass = { { "user1", "pass1" },
{ "user2", "pass2" },
{ "user3", "pass3" } };
String value1 = "userToCheck";
String value2 = "passToCheck";
boolean userOk = false;
for (String[] up : userPass)
if (value1.equals(up[0]) && value2.equals(up[1]))
userOk = true;
System.out.println("User authenticated: " + userOk);

- 413,195
- 112
- 811
- 826
if ((value1.equals("username1") && value2.equals("password1")) ||
(value1.equals("username2") && value2.equals("password2")))
I advise you to do some decent username/password checking because hardcoding is not secure (and flexible)

- 19,580
- 4
- 64
- 107
There are many ways to solve this, and others have answered it adequately, but looking at the bigger picture it looks like you might want to use a better data structure instead. Presumably all usernames are unique (i.e. no two users have the same name), and each user can have only one password. In that case, what you have is a Map<Username,Password>
(or perhaps simply Map<String,String>
).
From the documentation:
interface Map<K,V>
: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
In addition to the basic mapping functionality, there are implementations that preserves insertion order, or sorts on the keys (see Related Questions).
Here's an example usage:
import java.util.*;
public class MapUsernamePassword {
public static void main(String[] args) {
Map<String,String> passwordByUsername = new HashMap<String,String>();
passwordByUsername.put("jamesbond", "i~am:aWesoem!");
passwordByUsername.put("n00b", "pizza");
System.out.println(passwordByUsername);
// {jamesbond=i~am:aWesoem!, n00b=pizza}
System.out.println(passwordByUsername.containsKey("jamesbond"));
// true
System.out.println(passwordByUsername.get("jamesbond"));
// i~am:aWesoem!
System.out.println(passwordByUsername.containsKey("austinpower"));
// false
System.out.println(passwordByUsername.get("n00b").equals("pizza"));
// true
}
}
API references
Related questions

- 1
- 1

- 376,812
- 128
- 561
- 623
if (value1.equals("username1") && value2.equals("password1") || value1.equals("username2") && value2.equals("password2") ||....)

- 18,794
- 5
- 57
- 67