I am trying to write a coded that reads in a text file into an array list. However, I am unsure how to parse my text file into strings to correctly be put into an array list. Here is a sample text file that I need to use.
This should be the sample question.
2
one
two
three
four
0
4
6
My Java code below:
package javaapplication8;
import java.util.*;
import java.io.*;
public class JavaApplication8 {
public static void main(String[] args) throws IOException{
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
int numItems = Integer.parseInt(fScan.nextLine());
ArrayList<String> Questions = new ArrayList<String>();
for(int i=0; i < numItems; i++)
{
Questions.add(fScan.nextLine());
}
System.out.print("The array is: " + Questions);
}
From your comment about the variable
numLinesbelow, you don’t need to parse integers from the content so you can remove the line:Then to output every line to the array, you can use
Scanner.hasNextLine():