2016-04-27 105 views
-4

我正在使用shellort從輸入文件中查找總體。爲什麼我得到StringIndexOutOfBoundsException:字符串索引超出範圍:65

這裏是我的代碼:

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 
    } 
} 

我收到線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) 

如果我改變50-0它的工作原理,但我需要從點50取。 爲什麼我得到這個錯誤?

+2

因爲你沒有學會製作[mcve]。仔細閱讀該頁面。當你有,檢查所有相關的職位相同的標題那裏---------------> – Tunaki

+1

可能重複的[StringIndexOutOfBoundsException](http://stackoverflow.com/questions/7505947/的StringIndexOutOfBoundsException) – ochi

回答

0

似乎有些國家沒有足夠的長度來獲得從50到65的字符。 首先,你應該檢查你的countryArray包含什麼。只需使用debuger。

相關問題