随机选择的字符串

Random selected strings

我有一个文本文件,我正在尝试将每一行转换成一个 ArrayList。然后我必须从此 text.file 中随机取一行并将其显示在新的 JOptionPane 上。

我试图在 for 循环中实现它,但它总是只出现在我 text.file 的第一行。非常感谢,这是我的代码。

public void actionPerformed(ActionEvent e) {

    ArrayList<String> allQuestions = new ArrayList<String>();
    ArrayList<String> allRandomSelectedQuestions = new ArrayList<String>();
    File file = new File("C:/Users/User/Documents/NetBeansProjects/SummerExamProject/src/Questions2.txt");
    int numberOfRandomQuestions = 16;

    try {
        //Read line by line from the file  
        Scanner scan = new Scanner(file);

        while (scan.hasNextLine()) {

            String line = scan.nextLine();

            //  System.out.println(line);
            JOptionPane.showMessageDialog(null, line.replace("/", "\n"));

            scan.close();

            allQuestions.add(line); 
        }
    } 
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

    for(int i = 0; i < numberOfRandomQuestions; i++){
        Random randNum = new Random();

        int randQuestionIndex = randNum.nextInt(numberOfRandomQuestions);   
        String randomQuestion = allQuestions.get(randQuestionIndex); 
        allRandomSelectedQuestions.add(randomQuestion);
    }
}

这一行...

scan.close();

在你的 while 循环中,所以它在第一次通过循环读取一行后关闭文件。

将它移到循环之后(即在关闭的 culry-brace 之后)应该可以修复它。

问题是这样的:scan.close();。您将在用于阅读的同一循环中关闭扫描仪。将它移到循环体之外应该可以解决问题。

在while 循环后调用close 方法。发生了什么事,你在第一行之后关闭。所以 while 循环只在一次后停止。

 while (scan.hasNextLine()) {

          String line = scan.nextLine();
          //System.out.println(line);
          JOptionPane.showMessageDialog(null, line.replace("/", "\n"));
          allQuestions.add(line); 
    }
    scan.close();

试试这个。希望对你有帮助。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class StackTest {

    public static void main(String[] args) {
        actionPerformed();
    }

    public static void actionPerformed() {

        ArrayList<String> allQuestions = new ArrayList<String>();
        File file = new File("D:/me/test.txt");
        int numberOfRandomQuestions = 10;
        try {
            // Read line by line from the file
            Scanner scan = new Scanner(file);

            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                allQuestions.add(line);
            }
            scan.close();

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

        for (int i = 0; i < numberOfRandomQuestions; i++) {
            Random randNum = new Random();

            int randQuestionIndex = randNum.nextInt(numberOfRandomQuestions);
            System.out.println();
            String randomQuestion = allQuestions.get(randQuestionIndex);
            JOptionPane.showMessageDialog(null, randomQuestion.replace("/", "\n"));
        }
    }
}