java - 读取文件时,我尝试将每一行存储到相关的LinkedList中,但是无法读取第一个字符。这怎么样?

标签 java file-io linked-list charat

我正在尝试用Java制作琐事游戏,并且我需要从文本文件中读取信息,然后将数据存储在两个LinkedLists中的一个(无论是问题还是答案)中。从理论上讲,任何不是问题也不是答案的东西(例如空格或标题标题)将被忽略,并且不会添加到任何列表中。但是,我从来没有走那么远。

当我使用stn.charAt(0)时,它适用于文本文件中的第一行,但是没有后续行,即使在while循环的每次迭代之后重置了该值。我收到此错误:java.lang.StringIndexOutOfBoundsException: String index out of range: 0

我究竟做错了什么?

码:

import java.io.*;
import java.util.*;

public class Game 

{

    public static void main(String[] args) 

    {

        File pack = new File("SP21.txt");
        FileReader f;
        JFrame j = new JFrame();
        LinkedList<String> ans = new LinkedList<String>();
        LinkedList<String> qus = new LinkedList<String>();

        try 

        {

            f = new FileReader(pack);
            BufferedReader br = new BufferedReader(f);

            String st;
            String stn;
            while((st = br.readLine()) != null)

            {

                //This line removes all non-ascii characters, which is ridiculously beneficial to reading Q's and A's
                stn = st.replaceAll("[^\\p{ASCII}]" , "");

                char c = stn.charAt(0);

            }

            br.close();

        } catch (FileNotFoundException e) {

            JOptionPane.showMessageDialog(j , "File not found" + e , "Error" , JOptionPane.ERROR_MESSAGE);

        } catch (Exception e) {

            JOptionPane.showMessageDialog(j , "Whoops! Something went wrong! " + e , "Error" , JOptionPane.ERROR_MESSAGE);

        }

    }

}


附件为:

40-POINT SNAPSTART TO ROUND ONE

1.Name the last Plantagenet and Yorkist King of England.
A. RICHARD III
2. Of Denmark, Sweden or Finland, which country has no territory north of the Arctic Circle?
A. DENMARK
3. With what type of emergency should I associate the Heimlich Manoeuvre?
A. CHOKING (ON FOOD)
4. In what city is the headquarters of the Canadian Wheat Board?
A. WINNIPEG

30-POINT OPEN QUESTION - WRITERS

5. Which French author wrote The “Three Musketeers” and “The Count of Monte Cristo"?
A. ALEXANDRE DUMAS
6. Which Scottish novelist wrote his first historical romance in prose, entitled “Ivanhoe”?
A. SIR WALTER SCOTT
7. Which American writer is famous for “John Brown’s Body” and “The Devil and Daniel Webster”?
A. STEPHEN BENET

最佳答案

更换

stn = st.replaceAll("[^\\p{ASCII}]" , "");
char c = stn.charAt(0);




stn = st.replaceAll("[^\\p{ASCII}]" , "");
char c;
if(stn.length()>0) {
    c = stn.charAt(0);
}

关于java - 读取文件时,我尝试将每一行存储到相关的LinkedList中,但是无法读取第一个字符。这怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128108/

相关文章:

javascript - 分割链表

java - 如何测试实用程序项目的 final方法和静态方法?

java - 如何使用java获取Jenkins中的工作列表?

java - SwingWorker异常

c - 从文件中读取代码

c++ - 试图制作一个包含字符串 C++ 的链表

java - 使用 AspectJ 拦截请求范围内的所有 JDBC 调用并作为响应返回

java - 如何捕获在测试中创建的模拟类型的实例?

haskell - Haskell 中的并发文件读/写?

python - 在 python 中使用链表实现堆栈。 pop 方法的问题和有关可变性的问题