haoxiaolan 2022-03-15 21:37 采纳率: 34.7%
浏览 36
已结题

java while()循环的问题

while (true){
        System.out.println("请输入用户名");
        String user1 = scanner.nextLine();
    

        String password1 =null;
        System.out.println("输入密码");
        String password = scanner.nextLine();

        System.out.println("请确认密码");
        String dpassword = scanner.nextLine();
        if(password.equals(dpassword))    password1 = dpassword;
        else{
            System.out.println("密码不正确");
            continue;
        }

        String phone1 = null;
        System.out.println("请输入你的手机号");
        String phone = scanner.nextLine();
        if((phone.length() == 11) && ((phone.startsWith("13")) || (phone.startsWith("15")) || (phone.startsWith("17"))))
        {
             phone1 = phone;

        }else {
            System.out.println("手机号码格式不对");
            continue;
        }


        String birthday1 = null;
        System.out.println("请输入生日格式为 :yyyy-mm-dd");
        String birthday = scanner.nextLine();
        try {
            simpleDateFormat.parse(birthday);
            birthday1 = birthday;
        } catch (ParseException e) {
            e.printStackTrace();
            continue;
        }


        String email1 = null;
        System.out.println("请输入你的邮箱");
        String email = scanner.nextLine();
        if(email.contains("@")){
            email1 = email;
        }else continue;




        User u1 = new User(user1,password1,phone1,birthday1,email1);
        if(set.size() !=0 ){
            int i = 0;
            System.out.println();
            for(User us:set) {
                if (us.equals(u1)) {
                    System.out.println("已经有该用户,不可重复注册");
                    continue;
                }
                i++;
            }
            if(i == set.size()) set.add(u1);
        }else  set.add(u1);



        int a = -1;
        System.out.println("你输入0 或者非0的数字  0:停止注册用户信息显示用户信息,非0继续执行 ");
        a = scanner.nextInt();
        if(a == 0)  break;
        else continue;
    }

img

为啥我输入非0数字开始第二次循环的时候,不能输入用户名,

但是手机号或者其他输错格式 导致的再一次循环就可以输入用户名。这是这么原因?

我想要达到的结果
  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2022-03-15 22:03
    关注

    因为你输入非零数字后,输入缓冲区有换行符,nextLine遇到换行符就认为已经输入完了。所以就不需要你输入跳过去了
    nextLine前清空一下输入缓冲区

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月23日
  • 已采纳回答 3月15日
  • 创建了问题 3月15日

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格