在Java中,已知 String[] username = {"a123","b123","c123"}; String[] password = {"a007","b007","c007"};
时间: 2023-09-02 09:08:39 浏览: 182
可以通过以下方式进行用户名和密码的匹配验证:
1. 使用 Scanner 类从控制台输入用户名和密码,例如:
```
Scanner scanner = new Scanner(System.in);
System.out.print("请输入用户名:");
String inputName = scanner.nextLine();
System.out.print("请输入密码:");
String inputPassword = scanner.nextLine();
```
2. 使用 for 循环遍历 username 数组,查找与输入的用户名匹配的元素下标,例如:
```
int index = -1;
for (int i = 0; i < username.length; i++) {
if (username[i].equals(inputName)) {
index = i;
break;
}
}
```
3. 根据上一步查找到的下标,判断输入的密码和对应的 password 数组中的元素是否匹配,例如:
```
if (index != -1 && password[index].equals(inputPassword)) {
System.out.println("用户名和密码正确!");
} else {
System.out.println("用户名或密码错误!");
}
```
完整代码如下:
```
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
String[] username = {"a123", "b123", "c123"};
String[] password = {"a007", "b007", "c007"};
Scanner scanner = new Scanner(System.in);
System.out.print("请输入用户名:");
String inputName = scanner.nextLine();
System.out.print("请输入密码:");
String inputPassword = scanner.nextLine();
int index = -1;
for (int i = 0; i < username.length; i++) {
if (username[i].equals(inputName)) {
index = i;
break;
}
}
if (index != -1 && password[index].equals(inputPassword)) {
System.out.println("用户名和密码正确!");
} else {
System.out.println("用户名或密码错误!");
}
}
}
```
阅读全文