-4

I am using a shellsort to find the populations from an input file.

Here is my Code:

package assignment.pkg3;

import java.io.*;

import java.util.*;

public class Sorting{

   public static void main (String[] args) throws IOException
   {

      String[] countryArray = new String[238];
      String [] newStringArray = new String [238];
      Scanner stdIn = new Scanner(new File("C:\\Users\\talls_000\\Downloads\\CountryUnsortedFormat.txt"));

      //reads the file into the array
      while(stdIn.hasNext())
      {
         for (int i = 0; i < countryArray.length; i++)
         {
            countryArray[i] = stdIn.nextLine();
         }//end for
      }
      int j;
      int high = 65;
      String temp;
      //temp=countryArray[ i ].substring(50, 65);
      for( int gap = countryArray.length / 2; gap > 0; gap /= 2 )
      {
         for( int i = gap; i < countryArray.length; i++ )
         {
            temp=countryArray[ i ].substring(50,high);
            for( j = i; j >= gap && temp.compareTo( countryArray[ j - gap ] ) < 0; j -= gap )
            {
               countryArray[ j ] = countryArray[ j - gap ];
                countryArray[ j ] = temp;
            }


         } 
      }

      for (int i = 0; i < countryArray.length; i++)
      {
         System.out.println(countryArray[i]);
      }//end for 
   }
}

I receive the error on line 33: temp=countryArray[ i ].substring(50,high);

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 65
    at java.lang.String.substring(String.java:1950)
    at assignment.pkg3.Sorting.main(Sorting.java:33)

If I change 50 to 0 it works, but I need to take from spot 50. Why am I getting this error?

Dylan
  • 1
  • 1
  • 1
  • 2
    Because you didn't learn to make a [mcve]. Read that page carefully. When you have, check all the related posts with the same title there ---------------> – Tunaki Apr 27 '16 at 21:37
  • 1
    Possible duplicate of [StringIndexOutOfBoundsException](http://stackoverflow.com/questions/7505947/stringindexoutofboundsexception) – blurfus Apr 27 '16 at 21:39

1 Answers1

1

It seems that some country has not enough length to get chars from 50 till 65. At first you should check what your countryArray contains. Just use debuger.

CyberAleks
  • 1,545
  • 1
  • 14
  • 17