我是Java的新手,我正在创建一个java测验游戏作为一个类项目。我的问题在于该计划的游戏部分。我尝试使用for循环从文本文件中读取问题,答案,正确答案和每个问题的值。我的问题是我不知道如何在for循环中编写代码来显示问题和答案,并保存问题的正确答案和点值的值。这是文本文件中的格式:
Question
A) answer
B) answer
C) answer
D) answer
correct answer
point value
这是我的代码:
//importing dialog box tools, scanner tools, and file reading/writing tools
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
public class JavaQuiz
{
public static void main(String[],args) throws IOException
{
//Declaring and initializing variables
String userChoice, gameQuestion, gameAnswer;
int gameScore = 0, menuChoice = 0;
//Declaring file object
File infile = new File("Questions.txt");
//Declaring scanner object for file reading
Scanner fileInput = new Scanner(infile);
//Opening statement
JOptionPane.showMessageDialog(null, "Let's Begin!");
JOptionPane.showMessageDialog(null, "First Question!");
//Reading data from "Questions.txt"
for(int i=1; i<=7; i++) //there are 7 questions in the text file.
{
}
//Closing file
fileInput.close();
}
}
答案 0 :(得分:2)
用Java读取文件非常简单(至少在Java 8中)。你可以这样做:
List<String> lines = Files.readAllLines(Paths.get(PATHTOFILE));
Map<Character, String> answers = HashMap<>();
String question = lines.get(0);
answers.put('A', lines.get(1));
answers.put('B', lines.get(2));
answers.put('C', lines.get(3));
answers.put('D', lines.get(4));
Character answer = lines.get(5).charAt(0);
Integer value = Integer.parseInt(lines.get(6));
然后只需要一个函数返回一个对象,可能只是一个POJO,Question
,它包含所有信息。然后,您可以在代码中使用该问题。