Java中最先学到的输入方法就是用Scanner类,方便好用,根本就不会想到会在输入上出问题,结果还真遇到了。
问题描述起来太啰嗦,直接看代码运行的结果。(代码借用遇到同样问题的一位朋友写的,稍有修改)
import java.util.*;
public class ShiYan1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入数字:");
int option = input.nextInt();//read numerical value from input;
System.out.println(option);
System.out.println("请输入字符串1:");
String string1 = input.nextLine();//read 1st string (this is skipped)
System.out.println("请输入字符串2:");
System.out.println(string1);
String string2 = input.nextLine();//read 2nd string (this appears right after reading numerical value)
System.out.println(string2);
}
}
/*运行情况:
请输入数字:
2 //输入2,回车
2 //输出2,这里nextInt()输入输出正常。
请输入字符串1:
请输入字符串2:
//注意从这里开始是空了两行,因为输入2后的回车被下一个nextLine读取
//输出nextLine读取的回车
sun //接下来的nextLine正常读取字符串
sun
*/
通过上面的实例可以发现:这种交叉输入的时候Scanner读取会出现问题。
接下来我把我从大牛那里理解的原因分享一下:
注释:(英语不行凑合着看)
nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.
只读取整数类型数据, nextInt()在读取完输入后把光标放在读取数据的同一行,该数据的后面。
next(): read the input only till the space. It can't read two words separated by space. Also, next() places thecursor in the same line after reading the input.
只读取到空格,不能读取被空格分开的两个单词(也就是不能读取空格),并且在读取完后把光标放在读取数据的同一行,该数据的后面。(同上)
nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions thecursor in the next line.
读取整行的数据包括单词间的空格,到回车结束(也就是从开始读一整行包括回车),读取结束后,光标放在下一行开头。所以上面一题的原因:nextInt()只读取了数值2,剩下"\n"还没有读取,并将光标放在本行中2后面。接着nextLine()会读取"\n",并结束本次读取。
再看例子:
import java.util.*;
public class ShiYan2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//输入并输出一个整数
int n = in.nextInt();
System.out.println(n);
//输入并输出一个字符串
String s = in.next();
System.out.println(s);
//输入并输出一个字符串
String ss = in.nextLine();
System.out.println(ss);
}
}
/*
运行情况:
2 sun sun sun //输入,每个类型间用空格分开
2 //读取并输出2
sun //输出sun说明输出2后光标在2后面,所以next读取输出了sun
sun sun //输出了 sun sun说明上一个读取后光标在其后,但 sun sun前和中间有空格输出,说明nextLine一直读到本行结束并可以读取空格(还有回车,此处没举例)
*/
注意:回车表示一行输入结束。
解决办法:1、在交叉使用时可以用next()代替nextLine();
2、可以在nextInt()(或next())和nextLine()之间添加一个nextLine()用来吸收掉空格或回车;
3、其他。
举例:
import java.util.*;
public class ShiYan2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//输入并输出一个整数
int n = in.nextInt();
System.out.println(n);
in.nextLine();//添加nextLine吸收回车
//输入并输出一个字符串
String String1 = in.nextLine();
System.out.println(String1);
//输入并输出一个字符串
String s = in.next();
System.out.println(s);
//输入并输出一个字符串
String String2 = in.next();//改用next()
System.out.println(String2);
}
}
/*
修改前运行情况:
2
2
sun
sun
*/
/*
修改后运行情况:不做解释了
2
2
sun
sun
hello
hello
world
world
*/
逻辑估计有点乱请原谅。