@Tnext和nextLine的区别OC
java中next与nextLine用法区别:
next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
简单地说,next()查找并返回来自此扫描器的下一个完整标记。
完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串。
而nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
next(),nextInt()和nextFloat()看到空格符或回车符都认为读取结束,此时不会读取回车符。
回车符只会留在这里等待下一个可以读取回车符号的读取流来把这个回车符接收掉。
nextLine()也是以回车符为结束,并且只是以回车符结束,并且会读取回车符。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run1();
}
public void run1(){
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
String[] strArray = new String[count];
int[] intArray = new int[count];
// int count1 = 0;
// Scanner sc1 = new Scanner(System.in);
for (int i = 0; i < count && sc.hasNextLine(); i++) {
strArray[i] = sc.nextLine();
// System.out.println("这是第" + (i + 1) + "次输入,输入得是" + strArray[i]);
}
int sum;
for (int i = 0; i < count; i++) {
sum = 0;
char[] array = strArray[i].toCharArray();
for (int j = 0; j < array.length; j++) {
// System.out.print(array[i] + " ");
if(array[j] >= 48 && array[j] <= 57 ){
sum ++;
}
}
intArray[i] = sum;
}
for (int i = 0; i < count; i++) {
System.out.println(intArray[i]);
}
}
}
对于给定的一个字符串,统计其中数字字符出现的次数。
运行结果为:
3
28738yehe3
389eyheeh33w
0
6
5
(无法读取第三次输入,原因是nextLine()第一次自动读取了被next()去掉的回车符,又因为nextLine()以回车符结束,所以读取到的字符串为空,第二次和第三次可以从键盘正常输入值)
当把nextLine改为next发现程序可以正常接收三次字符串输入,
运行结果如下:
3
w82yw
2w988uw2
289yuw
2
5
3
Process finished with exit code 0
而其他的next的方法,如double nextDouble() , float nextFloat() , int nextInt() 等与nextLine()连用时都存在这个问题,解决的办法是:在每一个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。
int count = sc.nextInt();
String[] strArray = new String[count];
int[] intArray = new int[count];
// int count1 = 0;
// Scanner sc1 = new Scanner(System.in);
sc.nextLine();
for (int i = 0; i < count && sc.hasNextLine(); i++) {
strArray[i] = sc.nextLine();
// System.out.println(“这是第” + (i + 1) + “次输入,输入得是” + strArray[i]);
}
得到的结果也是正确的!
本文详细介绍了Java中Scanner的next()和nextLine()方法的区别。next()方法会跳过空格并只返回完整标记,而nextLine()则会读取包括空格在内的整个行。在使用next()等方法后,需要使用nextLine()来处理回车符残留问题,以避免影响后续输入。示例代码展示了nextLine()在不同场景下的行为。
1154

被折叠的 条评论
为什么被折叠?



