简体   繁体   中英

Comparing a String to an array of strings

Right basically what I'm trying to do is a very simple login screen to get to know swing.

My issue is I currently have a file pass.txt which is formatted like so:

Username = bob,tony,mike
Password = pass,pass2,pass3

in my Java file I get the strings by using:

String[] user = prop.getProperty("Username").split(",");

Now I then compare this with my text input from a JTextField however it always fails what I have is:

if (input2.equals(pass) && userin.getText().equals(user))

Now I'm guessing my issue is I have an array of strings and it's comparing it to a single string now what I want to do is go through the array and if any of them match I want it to take that match and use it if that makes sense, is there any way to go about this?

i think this may help you,because i think you have to check each user with his password int this array:

for(int i=0;i < user.size();i++){
  if(input2.equals(pass[i]) && userin.getText().equals(user[i])){
   //your code
  }
}

Assuming you have a pass array to match your user array, and every entry in user is guaranteed to have a corresponding entry in pass , then the following solution should work:

int index = Arrays.asList(user).indexOf(userin.getText());
String password = pass[index];

if (password.equals(input2)) {
    // Successful authentication
} else {
    // Authentication failed
}
  • Arrays.asList(user).indexOf(userin.getText()) will get the index of the user in the list (in your example, "bob" => 0; "tony" => 1; "mike" => 2).
  • password is then the password string at that same index (in your example, "pass" => 0; "pass2" =>1; "pass3" => 2).
  • Then the if compares the password associated with the user ( password ) with the password that was input in the dialog ( input2 ).

您必须搜索用户名表,找到引入的用户名的位置,然后检查该位置上的密码是否等于用户引入的密码。

You have to somehow search the array for the string you're looking for. There are a bunch of ways of doing this, I'll outline one method.

int index = 0;
for (String s : user) {
    if (s.equals(userin.getText()) {
        // the username matches! now check to see if the password at the _same index_ matches
        if (pass[index].eqals(input2.getText()) {
            // correct username and password!
        } else {
            // bad password!
        }
    }
    ++index;
}

I'm assuming that you have a password array called pass and that the indices match those of the user array. ( user[i] 's password is pass[i] )

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