javajava.util.scanner

Assigning 1 line of a txt file to a string via scanner


As the title explains I'm trying to get each line assigned to a string (My ultimate goal would be to have it pull a line from a text file, then use the line below as an answer, then to repeat this until the file is finished) right now I've only got it to assign the whole file to a string (line). Here's my code -

import java.io.*;
import java.util.Scanner;
import java.lang.*;
import javax.swing.JOptionPane;

public class Test {

public static void main(String[] args) {

    // Location of file to read
    File file = new File("a.txt");

    try {

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            JOptionPane.showInputDialog("" + line);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
     System.out.println("Can't find file");  
    }

}
}

Any help appreciated, or workarounds using other imports - thanks.


Solution

  • You could use an ArrayList of String to store the lines read from the file:

    public static void main(String[] args) {
    
        // Location of file to read
        File file = new File("a.txt");
        List<String> lines = new ArrayList<String>();
    
        try {
    
            Scanner scanner = new Scanner(file);
    
            while (scanner.hasNextLine()) {
                lines.add(scanner.nextLine();
            }
            scanner.close();
        } catch (FileNotFoundException e) {
         System.out.println("Can't find file");  
        }
    }
    

    The array list lines will contain the lines of the file in the order that they appeared in the file, meaning you can iterate over the lines array where lines.get(i) would be the question and lines.get(i+1) would be the answer:

    for (int i = 1; i < lines.size(); i+=2)
    {
        String question = lines.get(i - 1);
        String answer   = lines.get(i);
        JOptionPane.showInputDialog("Question: " + question + " Answer:" + answer);
    }