关于Scanner中的next()和nextLine()连用的问题

        Scanner scanner=new Scanner(System.in);
        System.out.print("输入一个数:");
        int a=scanner.nextInt();
        System.out.print("请输入用户名:");
        String userName=scanner.nextLine();
        System.out.print("请输入密码:");
        String passWord=scanner.nextLine();
        if ((userName.equals("admin")&&passWord.equals("123"))||
                (userName.equals("zhangsan")&&passWord.equals("zhangsan123"))){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }

nextLine()是以回车作为结束符,nextLnt()是以空格作为结尾,按下enter键之后,a获取到值了,但enter还在上一行的末尾没有被获取。

于是userName就只会获取到上一行末尾的换行符

解决方法:

在获取userName之前,再调用一次nextLine()方法,就能正常获取到值

        scanner.nextLine();
        String userName=scanner.nextLine();
        System.out.print("请输入密码:");

猜你喜欢

转载自www.cnblogs.com/wzydblog/p/12538942.html
今日推荐