import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/Quiz")
public class Quiz extends HttpServlet {
private static final String ANSWER = "answer";
private static final String SCORE = "score";
private static final String NUMBER = "number";
private static final String QUESTIONS = "questions";
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// 最初の問は GET
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(
"text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("
");
int i, number = 0, score = 0;
ArrayList questions;
HttpSession session = request.getSession(true);
if (session.isNew()
|| session.getAttribute(QUESTIONS) == null) {
// 最初の問
questions = new ArrayList();
File f = new File(getServletContext()
.getRealPath("/WEB-INF/quiz.txt"));
BufferedReader in
= new BufferedReader(new InputStreamReader(
new FileInputStream(f), "UTF-8"));
String line="";
while ((line = in.readLine()) != null) {
line = line.trim();
if (line.trim().equals("")) continue;
// 空白の1つ以上の繰返し
questions.add(line.split("\\s+"));
}
in.close();
session.setAttribute(QUESTIONS, questions);
out.println("ようこそ QUIZへ!
");
out.println(" では最初の問題です。
");
}
else {
// 最初の問ではない
try {
number = (int)session.getAttribute(NUMBER);
score = (int)session.getAttribute(SCORE);
questions = (ArrayList)
session.getAttribute(QUESTIONS);
String[] tokens = questions.get(number - 1);
int a = Integer.parseInt(
tokens[tokens.length - 1]);
int answer = Integer.parseInt(
request.getParameter(ANSWER));
if (a == answer) { // a は最後の文字
out.println("正解です。
");
score++;
} else {
out.println("残念でした。
");
}
} catch (Exception e) {
session.removeAttribute(QUESTIONS);
out.println(
"想定外のアクセスでエラーが起こりました。"
+ "タブを閉じるかリロードしてください。");
e.printStackTrace(out);
out.println("");
out.close();
return;
}
}
if (number >= questions.size()) { // 終
out.println("
");
out.println("これで QUIZは終わりです。
");
out.printf("正解数は、%d問でした。%n", score);
session.removeAttribute(QUESTIONS);
}
else { // 次の問を表示
String[] tokens = questions.get(number);
out.println("次の問: " + tokens[0] + "
");
out.println("");
number++;
session.setAttribute(NUMBER, number);
session.setAttribute(SCORE, score);
}
out.println("