input.next()和input.nextLine()都是Scanner的读取方法,但读取范围不同:
next():读取下一个由空白字符分隔的单词。空格、换行、制表符都会作为分隔符。nextLine():读取当前行剩余的全部内容,可以包含空格,直到遇到换行符。
eg输入:
Hello Java WorldString a = input.next(); // 得到 "Hello" String b = input.nextLine(); // 可能得到 " Java World"如果字符串不包含空格,例如Ice,使用next()就足够:
/* 输入: Ice Ice */ String str1 = input.next(); String str2 = input.next();如果需要读取完整的一行字符串,例如Hello Java,应使用nextLine()。
注意:调用nextInt()、next()后直接调用nextLine(),nextLine()可能只读取前一个输入留下的换行符。此时通常先额外调用一次input.nextLine()清除换行,再读取真正的一行。
解释如下:
可以把Scanner的输入想象成一条字符流:
25\nHello Java\n其中:
25是数字\n是按下回车产生的换行符Hello Java是下一行内容
调用:
int age = input.nextInt();nextInt()只读取数字25,不会读取后面的换行符\n。
此时输入流仍然是:
\nHello Java\n如果马上调用:
String text = input.nextLine();nextLine()会从当前位置读取到当前行末尾,而当前位置一开始就是换行符,所以它只能读到一个空字符串。
因此常见写法是:
int age = input.nextInt(); input.nextLine(); // 清除数字后面的换行符 String text = input.nextLine(); // 读取真正的下一行完整示例:
Scanner input = new Scanner(System.in); int age = input.nextInt(); input.nextLine(); // 清除回车 String message = input.nextLine(); System.out.println(age); System.out.println(message);输入:
18 Hello Java输出:
18 Hello Java但如果连续使用next(),通常不需要额外处理,因为next()会跳过前面的空白字符:
String first = input.next(); String second = input.next();核心区别是:nextInt()和next()读取内容本身,nextLine()读取到整行结束;前两者通常不会替你消费行尾的换行符。