我正在尝试用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);
}