Scanner类的nextInt()方法疑问

先上代码
第一个:

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int count = sc.nextInt();
        String line;
        long a;
        long b;
        long c;
        boolean[] booleans = new boolean[count];
        sc.nextLine();
        for (int i = 0; i < count; i++) {
            line = sc.nextLine();
            a = Integer.valueOf(line.split(" ")[0]);
            b = Integer.valueOf(line.split(" ")[1]);
            c = Integer.valueOf(line.split(" ")[2]);
            booleans[i] = (a + b > c);
        }
        for (int i = 0; i < count; i++) {
            System.out.println("Case #" + (i + 1) + ": " + booleans[i]);
        }
    }
}

第二个:

import java.util.Scanner;
public class Main{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        boolean[] result = new boolean[n];
        for(int i = 0; i < n; i++)
        {
            long a = sc.nextLong();
            long b = sc.nextLong();
            long c = sc.nextLong();
            if((c-a)<b) result[i] = true;
            else result[i] = false;
        }
        for(int i = 0; i < n; i++)
            System.out.println("Case #" + (i+1) + ": "+result[i]);
    }
}

两段代码几乎一样,但是牛客网上编译运行,第二个完全通过,第一个会报异常,异常出现在int count = sc.nextInt();这一句,如果输入一个非int类型的数据会有异常,我很疑问,第二段代码也有sc.nextInt();为什么不会报异常?求大神解答

#笔试题目##Java#
全部评论
nextInt后不能接着用nextLine
点赞 回复
分享
发布于 2019-08-26 19:08
我也很好奇为什么
点赞 回复
分享
发布于 2019-08-27 08:52
联易融
校招火热招聘中
官网直投
判卷机很奇怪的,一般出现这种问题全部nextLine再去处理字符串比较稳妥
点赞 回复
分享
发布于 2019-08-27 09:13

相关推荐

团子 行业运营 n*15.5
点赞 评论 收藏
转发
1 1 评论
分享
牛客网
牛客企业服务