-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);
        }
    }
}
4
  • The 15th character in your string does not exist. Your string is shorter than that. Commented Sep 26, 2016 at 12:09
  • does every word has 21 characters or more? Commented Sep 26, 2016 at 12:09
  • 1
    Possible duplicate of Java substring : string index out of range Commented Sep 26, 2016 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. Commented Sep 27, 2016 at 7:36

1 Answer 1

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.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.