-1

这是我在 mapreduce 中使用并获得空指针异常的代码。我通过配置传递一个变量,将其作为字符串获取并解析并存储在一个 int 数组中并处理它——

  int[] results;

        public void configure(JobConf job) {
            // targetPeriod = Integer.parseInt(job.get("Predict"));
            String[] pred = job.get("Predict").split(",");
            results = new int[pred.length];

            for (int i = 0; i < pred.length; i++) {
                try {
                    results[i] = Integer.parseInt(pred[i]);
                } catch (NumberFormatException nfe) {
                }
                ;
            }




        protected void reduce(final IntWritable key, final Iterable<Text> values,
                final Context context) throws IOException, InterruptedException {

            // int targetPeriod = Integer.parseInt(predict.trim());
            String predictfin = null;
            // int targetPeriod = 10;
        "EXCEPTION HERE"---->
            double[] projectedCumulativeScoreAtTargetPeriod = new double[results.length];
            // Participant participant = new Participant(values,targetPeriod);
            for (int i = 0; i < results.length; i++) {
                Participant participant = new Participant(values, results[i]);




14/07/25 15:23:12 INFO mapred.JobClient: Task Id : attempt_201407110824_0728_r_000000_0, Status : FAILED
java.lang.NullPointerException
        at ProjectionReducer.reduce(ProjectionReducer.java:38)
        at ProjectionReducer.reduce(ProjectionReducer.java:1)
        at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:177)
        at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:649)
        at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:418)
        at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:396)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
        at org.apache.hadoop.mapred.Child.main(Child.java:249)
4

3 回答 3

2

您之前很可能没有运行过 configure 方法,因此int[] results当您调用results.length. 为了能够访问它的方法和变量,您必须在之前对其进行初始化,但是由于您的错误显示空指针异常,这是因为int[] results尚未初始化,因此您需要确保在之前对其进行初始化你得到它的长度属性。

于 2014-07-25T16:08:38.507 回答
1

问题是结果变量在抛出 NPE 的行上为空。现在您应该通过在违规行之前测试 null 和/或其内容的变量来验证这一点,然后回顾您的代码以了解原因。也许您在调用configure 方法之前调用了 reduce,但根据您发布的内容很难判断。

最重要的是,您需要学习调试 NPE 的一般技术——检查有问题的行上的变量,找到为 null 并引发异常的变量,然后回溯到代码中找出原因。你会一次又一次地遇到这些虫子,相信我。

您还需要提高您的搜索技能,因为此类问题每天在此站点上被问到不止一次。如果我能找到一个好的重复答案(我认为我们使用的常用答案不太好),我将删除此答案并将此线程锁定为重复。

于 2014-07-25T16:01:04.913 回答
0

我认为您的变量尚未初始化,这就是引发 NullPointerException 的原因。

于 2014-07-25T17:26:19.963 回答