nextInt(nextFloat nextByte), next, nextLine()
nextLine会以回车符作为截至符,会将回车符连同之前所有的字符都读取出来,将回车符丢掉,把之前的所有字符组合成一个完成的字符串,然后将完整的字符串交还给我们
next 会以回车和空格作为截至符,但是不读取回车与空格
nextInt会以回车符作为截至,只读取回车符之前的所有字符,回车符留在队列中
例子:假设输入账号为:abc 密码为:123
System.out.println("请输入账号:");
String name = input.nextLine();
System.out.println("请输入密码");
int password = input.nextInt();
/*
请输入账号:
abc
请输入密码:
123
接收到了账号:abc
接收到了密码:123*/
此时消息队列:input.nextLine()产生阻塞效果,等待用户在消息队列中输入账号,等待用户敲下回车完成输入之后,nextLine()读取“abc\n”, 选取“abc”作为输出,
后面再执行input.nextInt(),再次等待用户输入密码,
nextInt()读取回车符前面的内容“123”作为输出,回车符留在消息队列中。
如果将上述代码的顺序进行调换会产生什么结果呢?
System.out.println("请输入密码:");
int password = input.nextInt();
System.out.println("请输入账号:");
String name = input.nextLine();
/*
请输入密码:
123
请输入账号:
接收到了账号:
接收到了密码:123
*/
input.nextInt()等待用户输入完成,读取“123”,将回车符留在了消息队列中,所以当input.nextLine()读取消息队列时,发现队列中已经有了回车符,就认为输入结束了,那么他读取回车符以及回车符之前的内容,并把回车符之前的内容作为输出,但是此时消息队列中的回车符前方并没有任何字符,所以input.nextLine()返回的是一个空字符串 “” 。
如何避免第二种情况的出现?
- 采用input.nextLine();读取nextInt剩余回车符
- 采用next的方法,next的读取方式与nextInt一样,不读取回车符
- 将账号和密码都采用nextLine方法读取,再使用包装类进行数据类型转换
Scanner input = new Scanner(System.in);
System.out.println("请输入密码:");
String password = input.nextLine();
System.out.println("请输入账号:");
String name = input.nextLine();
int value = Integer.parseInt(password);
System.out.println("接收到了账号:"+name);
System.out.println("接收到了密码:"+value);