【发布时间】:2011-10-23 18:14:17
【问题描述】:
我正在为 Java 课程创建一个真/假测试,该课程将答案键和每个用户各自的答案数组存储为 BitSet。然后将这些 BitSet 序列化为持久的顺序二进制文件,以便稍后由另一个应用程序对它们进行评分。
除了我第一次调用request.readLine() 之外,一切都完美无缺,这是我的system.in inputstreamreader,它检索用户的答案。出于某种原因,无论输入什么,它都会将第一个答案设置为 null,就好像它遇到了 EOF。
CreateTest.java(从 txt 文件读取/显示问题,收集用户答案,将它们存储在 .bin 文件中)
public class CreateTest
{
private static BufferedReader request;
private static BufferedReader response;
private static String answers, userName;
private static ObjectOutputStream result;
public static void main(String[] args)
{
response = new BufferedReader(new InputStreamReader(System.in));
try
{
request = new BufferedReader(new FileReader("test.txt"));
}
catch(FileNotFoundException fnfe)
{
System.out.println("Test.txt was not found. Please fix your crappy file system.");
System.exit(1);
}
System.out.println("Welcome to THE TEST\n\n" +
"Please respond with only \"t\" for true or \"f\" for false.\n" +
"This application is case-insensitive.\n" +
"DON'T GET EATEN BY THE GRUE!");
System.out.println("\nPlease enter your name: ");
try
{
userName = response.readLine().replaceAll("\\s", "");
System.out.println("\n\n");
result = new ObjectOutputStream(new FileOutputStream(userName + "TestAnswers.bin"));
}
catch(IOException e1) { e1.printStackTrace(); }
try {
for(int i=0; i<24; i++)
{
System.out.println(request.readLine());
recordResponse();
}
System.out.println("Thank you for attempting THE TEST. You probably failed.");
result.writeObject(new BitMap(answers));
close();
} catch (IOException e) { e.printStackTrace(); }
}
public static void recordResponse() throws IOException
{
String currentAnswer = response.readLine();
//diagnostic
System.out.println("Answer: " + answers);
if(currentAnswer.equals("t")||
currentAnswer.equals("T")||
currentAnswer.equals("f")||
currentAnswer.equals("F"))
{ answers += currentAnswer + " -- "; }
else
{
System.out.println("What, you can't read or somethin'?. Enter(case-insenstive) T or F only pal." +
"Try it again.");
close();
System.exit(1);
}
}
public static void close() throws IOException
{
request.close();
response.close();
}
来自 BitMap.java 的相关构造函数(将传递的参数解析为 BitSet,提供按位运算)
public BitMap(String s) throws IndexOutOfBoundsException,ArithmeticException
{
try
{
if(s.length() > 25) { throw new IndexOutOfBoundsException(); }
StringTokenizer answers = new StringTokenizer(s);
for(int i=0; i<bitString.size(); i++)
{
String currentToken = answers.nextToken();
if(currentToken.equals("t") || currentToken.equals("T")) { bitString.set(i); }
else if(currentToken.equals("f") || currentToken.equals("F")) { bitString.clear(i); }
}
}
catch(IndexOutOfBoundsException ioob){System.out.println("Sorry bub, too many answers.");}
}
我为大量代码道歉,但我认为更多信息总比不够好。
【问题讨论】:
-
“text.txt”在文本编辑器中是什么样子的?
-
非常简单。它只有 25 个问题,每行一个问题以问号结尾。没有前导或尾随空格。喜欢的话可以发。这件事真是让人头疼。我从不喜欢 Java,他们用 Java 教授编程课程的事实让我发疯。我主要是 PHP 程序员。
标签: java readline bufferedreader