java中的nextLine()方法读取不到最后一行

题目要求是读入这样的数据

3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95

看到这样的格式,我想到了用nextLine()方法来按行读取,格式如下

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        String[] scores = new String[num];
        for (int i = 0; i < num; i++) {
    
    
                scores[i] = sc.nextLine();
        } 
        for (String score : scores) {
    
    
            System.out.println(score);
        }

但是,采用这样的方式每次都会遗漏最后一行,后续的操作会导致越界
在这里插入图片描述
查阅资料后,得到了一些收获:

1.我们读入的所有数据都是先存入缓冲区
2.Scanner实际上是从缓冲区读入以空格,\t,\n,\r分隔的字符
3.缓冲区读入了第一个整数之后,留下了\r,而\n是next()的分隔符,所以就相当于是我们循环的第一个nextline()被浪费掉了

#### 改进办法 读入整数之后加一个nextLine()清一下缓冲区
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        String[] scores = new String[num];
        sc.nextLine();
        for (int i = 0; i < num; i++) {
    
    
                scores[i] = sc.nextLine();
        }
        for (String score : scores) {
    
    
            System.out.println(score);
        }

在这里插入图片描述

这样就可以解决问题了

猜你喜欢

转载自blog.csdn.net/qq_45689267/article/details/108211220
今日推荐