Java使用数组实现注册登录功能校验失败问题咨询
问题排查与修复
首先明确:用数组实现账号注册登录功能是完全可行的,你遇到的报错是代码逻辑错误导致的,核心问题有3个:
- 类型不匹配、对比对象错误:你注册时的账号密码存在
int[]类型的数组中,登录时读取的是String类型的输入,直接用equals对比字符串和数组对象,二者类型完全不同,永远返回false。 - 没有遍历数组做匹配:你存储了多组账号密码,校验时需要遍历所有已注册的账号,逐一对比账号密码是否匹配,不能直接拿输入和整个数组对比。
- 数据类型设计不合理:用int存储账号密码适用场景非常有限,无法支持带字母、特殊字符的账号密码,建议改用String类型存储。
修正后的代码
import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("请输入要注册的账号数量:"); int n = s.nextInt(); s.nextLine(); // 吃掉nextInt留下的换行符 // 改用String数组存储账号密码,适配更多场景 String[] regId = new String[n]; String[] regPass = new String[n]; // 注册逻辑 for(int i = 0; i < n; i++){ System.out.println("请输入账号:"); regId[i] = s.nextLine(); System.out.println("请输入密码:"); regPass[i] = s.nextLine(); } // 打印所有已注册账号 System.out.printf("%-10s %-20s\n", "账号", "密码"); for(int i = 0; i < n; i++){ System.out.printf("%-10s %-20s \n", regId[i], regPass[i]); } // 登录环节 System.out.println("=========================="); System.out.println("==========登录==========="); System.out.println("=========================="); System.out.println("请输入账号:"); String inputId = s.nextLine(); System.out.println("请输入密码:"); String inputPass = s.nextLine(); // 校验逻辑:遍历所有账号逐一匹配 boolean loginSuccess = false; for(int i = 0; i < n; i++){ if(inputId.equals(regId[i]) && inputPass.equals(regPass[i])){ loginSuccess = true; break; } } if(loginSuccess){ System.out.println("欢迎登录"); }else{ System.out.println("账号或密码错误"); } s.close(); } }
内容的提问来源于stack exchange,提问作者Martin Lee
相关产品推荐
相关产品推荐

