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

…衆ロ難τιáo~ 提交于 2019-12-24 13:12:37

问题


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.


回答1:


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);
}



回答2:


As it is implemented now, your line variable only contains the last line of the file at the end of the execution. If you want to store each line you could put them in an ArrayList of Strings:

ArrayList<String> lines = new ArrayList<String>();
....
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    lines.add(line);
    JOptionPane.showInputDialog("" + line);
}


来源:https://stackoverflow.com/questions/9134665/assigning-1-line-of-a-txt-file-to-a-string-via-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!