Why is my array the only line of the last line of the file?

I am writing a program in which I need to pass all file data into an array, line by line. When I display a row, the only thing in the array is the last row. I need an array to have all the lines of the file so that I can select the index of the array.

Here is the code so far,

 while(inputFileTest.hasNext()) //counts amount of lines in the file
{
  count++;
  inputFileTest.nextLine();
}
fileTest= new File("TestBank.txt");
inputFileTest= new Scanner(fileTest);
String[] testArr=new String[count];

while(inputFileTest.hasNext()) 
{
  int i=0;
  String line= inputFileTest.nextLine(); 
  testArr= line.split("\n");
  testArr[i]=testArr[0];
  i++;
}
//int i=rand.nextInt(testArr.length);
for(String test:testArr)
  System.out.println(test);

      

}}

+3


source to share


1 answer


while(inputFileTest.hasNext()) 
{
  int i=0;

      

Should be

 int i=0;
while(inputFileTest.hasNext()) 
{

      



You set it to zero all the time. Move that to the end of the while loop and you should be fine.

And also, as bastijn commented, you are also avoiding the array. so it should be

  String[] ta= line.split("\n");
  testArr[i]=ta[0];

      

+5


source







All Articles