2014-09-18 1 views
0

Я продолжаю получать эту ошибку для цикла while: java.lang.ArrayIndexOutOfBoundsException; Это значение: прочитайте новые данные в массиве имен из «Input.txt» по одной строке в строке и поместите их в массив. Количество строк в файле должно быть таким же, как количество ячеек в массиве.читать новые данные в массив имен из input.txt

// Open an input textfile named "Input.txt". 
    File f = new File("Input.txt"); 
    Scanner inputFile = new Scanner(f); 
    System.out.println("\nThe array contents:"); 

    // Read new data into the array of names from "Input.txt" one String per line, and places them in an array. 
    //The number of Strings in the file must be the same as the number of cells in the array. 
    String[] input = new String [5]; 

    int k=0; 
    while (inputFile.hasNext()) 
    { 
     String str = inputFile.nextLine(); 
     input[k]=str; 
     k++; 
    } 
    inputFile.close(); 




    //Print the new array contents on the screen 
    PrintWriter pw = new PrintWriter("Input.txt"); 
    for(String str : array) 
     pw.println(str); 
    pw.close(); 

} 

/** 
* Method printOnScreen sends the entire contents of an 
* array to the Screen using an "enhanced for" loop. 
* 
* @param array the array of Strings be printed on Screen 
* 
*/ 
public static void printOnScreen(String[] args) 
{ 
    for(String val : args) 
     System.out.println(val); 
} 
+0

Попробуйте поместить строки в «ArrayList», а затем использовать метод «toArray()» в «ArrayList». – LearningDeveloper

ответ

0

Вы получаете ArrayIndexOutOfBoundException, это означает, что ваш файл имеет более 5 строк и массив строк только длины 5, так исключение. Если вы хотите прочитать 5 имен из файла «input.txt», то разорвать петлю, когда к> 5

while (inputFile.hasNext()) 
{ 
    if(k>5) break; 
    String str = inputFile.nextLine(); 
    input[k]=str; 
    k++; 
} 

или если вы хотите прочитать весь файл, то вам нужно использовать массив, размер которого не определен когда создается, что-то вроде динамического массива: ArrayList

List<String> input = new ArrayList<String>(); 

while (inputFile.hasNext()) 
{ 
    String str = inputFile.nextLine(); 
    input.add(str); 
} 
0

Кажется, ваш размер массива короток. Если вы не уверены в размере массива, я предлагаю вам использовать ArrayList.

List<String> input = new ArrayList<String>(); 

int k=0; 
while (inputFile.hasNext()) 
{ 
    String str = inputFile.nextLine(); 
    input.add(str); 
} 
inputFile.close(); 
0

рабочий пример

public class Test2 { 

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

     BufferedReader input = new BufferedReader(new FileReader("d:\\myFile.txt")); 

     String str; 

     List<String> list = new ArrayList<String>(); 
     while ((str = input.readLine()) != null) { 
      list.add(str); 
     } 

     String[] stringArr = list.toArray(new String[0]); 

     System.out.println("\nThe array contents:"); 
     for (String val : stringArr) 
      System.out.println(val); 

    } 

} 

Выходные

Содержимое массива:

stack 
overflow 
is 
good 

Ввод текста файлаmyFile.txt

stack 
overflow 
is 
good 
Смежные вопросы