You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现登录失败时允许用户重新输入Student ID和password?

修复学生登录验证的重新输入问题

原代码存在的问题

  • 仅执行一次输入验证,账号或密码错误后无法重新输入
  • 第二个循环逻辑错误:仅检查第一个学生的ID就判定结果,忽略列表中其他匹配项;登录状态判断位置不合理

修改后的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class StudentLogin {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        List<Student> listOfStudents = // 替换为你的学生列表初始化逻辑
        Student loggedInStudent = null;

        System.out.println("*** 欢迎回来,同学 ***");

        // 用do-while循环实现错误后重新输入
        do {
            System.out.println("请输入你的学号:");
            String studentID = br.readLine();

            System.out.println("请输入你的密码:");
            String password = br.readLine();

            loggedInStudent = null;
            boolean isStudentExists = false;

            // 一次遍历完成学号存在性与密码正确性验证
            for (Student student : listOfStudents) {
                if (student.getStudentID().equals(studentID)) {
                    isStudentExists = true;
                    if (student.getPassword().equals(password)) {
                        loggedInStudent = student;
                        break;
                    }
                }
            }

            // 根据验证结果输出对应提示
            if (loggedInStudent != null) {
                System.out.println("登录成功!");
            } else if (!isStudentExists) {
                System.out.println("学号错误,请重新输入!");
            } else {
                System.out.println("密码错误,请重新输入!");
            }

        } while (loggedInStudent == null); // 未登录成功则重复循环

        // 登录成功后的后续操作示例
        System.out.println("欢迎你," + loggedInStudent.getStudentName());
    }
}

// 假设的Student实体类
class Student {
    private String studentID;
    private String password;
    private String studentName;

    public String getStudentID() {
        return studentID;
    }

    public String getPassword() {
        return password;
    }

    public String getStudentName() {
        return studentName;
    }

    // 构造方法、setter等必要代码
}

关键修改点

  • 用do-while循环包裹输入与验证流程,确保未登录成功时用户可重新输入
  • 新增isStudentExists标记,精准区分"学号不存在"和"密码错误"两种错误场景
  • 优化验证逻辑,一次遍历完成所有判断,避免冗余循环
  • 修正原代码中错误的循环判断逻辑,防止误判

内容的提问来源于stack exchange,提问作者Ching Kwok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:35:22