代码给出“java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:14”

时间:2016-09-26 12:08:35

标签: java string hadoop mapreduce

以下代码为我提供了 "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"

请指导我的代码有什么问题。

public class max_temp {

    public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        public String y;
        public String a;
        public Double t;

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {

            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                y = word.toString();
                a = y.substring(7,14);
                t = Double.parseDouble((y.substring(35,41).trim()));

                word.set(a);              

               // 27516201501012.424-156.6171.32-18.3-21.8-20.0-1   9.90.00.00C-19.2-24.5-21.983.973.777.                                
               context.write(word, one);
           }
       }
   }

   public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
       private IntWritable result = new IntWritable();

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

            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果你附加了堆栈跟踪会更容易。无论如何,问题是,你正在调用长度小于15的substring(7,14)的{​​{1}} .Java不知道该做什么,因此抛出异常。< / p>

问题在于您的应用逻辑。如果您使用String,则必须确保substring(7,14)足够长或使用String阻止。

try-catch