-1

the following code gives me "java.lang.StringIndexOutOfBoundsException: String index out of range: 14"

Please guide me on what is wrong with my code.

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);
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • The 15th character in your string does not exist. Your string is shorter than that. – Bathsheba Sep 26 '16 at 12:09
  • does every word has 21 characters or more? – SMA Sep 26 '16 at 12:09
  • 1
    Possible duplicate of [Java substring : string index out of range](http://stackoverflow.com/questions/953527/java-substring-string-index-out-of-range) – xenteros Sep 26 '16 at 12:19
  • Did my answer help you? If yes, please mark it as a solution by clicking on the gray tick below the answer score. – xenteros Sep 27 '16 at 07:36

1 Answers1

0

It would be easier if you attached the stacktrace. Anyway, the problem is, that you're calling the substring(7,14) of the String which has length smaller then 15. Java doesn't know what to do and therefore throws an exception.

The problem is with your app logic. If you use substring(7,14) you have to be sure that the String is long enough or use try-catch block.

try {
    String s = s.substring(7,14);
} catch (StringIndexOutOfBoundsException e) {
    //somehow process the situation in which the string is too short.
}
xenteros
  • 15,586
  • 12
  • 56
  • 91