3

I am writing a program where I have to transfer all the data of a file to an array, line by line. When I display the line though, the only thing in the array is the last line. I need the array to have all the lines of the file so I can select an 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);

} }

J.D
  • 41
  • 1
  • Possible duplicate of [How to use readline() method in Java?](http://stackoverflow.com/questions/8560395/how-to-use-readline-method-in-java) – jediz Apr 09 '17 at 20:16

1 Answers1

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

Should be

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

You are setting it to zero all the time. Move that to top of while loop, and you'd be fine.

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

  String[] ta= line.split("\n");
  testArr[i]=ta[0];
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307