1
0
Fork 0
mirror of https://gitlab.com/kauron/jstudy synced 2025-09-30 12:51:10 +02:00
jstudy/src/main/java/es/kauron/jstudy/model/TestItem.java
2016-06-12 16:04:56 +02:00

101 lines
3.1 KiB
Java

package es.kauron.jstudy.model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.io.*;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class TestItem {
public static final String TAB = "\t", COLONS = "::", SEMICOLON = ";", COMMA = ",";
private StringProperty question, answer;
public TestItem(SimpleStringProperty question, SimpleStringProperty answer) {
this.question = question;
this.answer = answer;
}
public TestItem(TestItem item) {
this(item.getQuestion(), item.getAnswer());
}
public TestItem(String question, String answer) {
this(new SimpleStringProperty(question), new SimpleStringProperty(answer));
}
public String getQuestion() {
return question.get();
}
public StringProperty questionProperty() {
return question;
}
public String getAnswer() {
return answer.get();
}
public StringProperty answerProperty() {
return answer;
}
public boolean isValid() {
return !question.get().isEmpty() && !answer.get().isEmpty();
}
public boolean checkAnswer(String answer, boolean sensible) {
return sensible ? getAnswer().equals(answer) : getAnswer().equalsIgnoreCase(answer);
}
public static void saveTo(File file, List<TestItem> data) {
try {
OutputStreamWriter writer = new FileWriter(file);
for (TestItem item : data) {
writer.write(item.getQuestion() + "::" + item.getAnswer() + "\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<TestItem> loadFrom(File file, String separator) {
List<TestItem> list = new ArrayList<>();
try {
Scanner in;
switch (separator) {
case COMMA:
case SEMICOLON:
case TAB:
in = new Scanner(new FileInputStream(file), "ISO-8859-1");
break;
default:
in = new Scanner(file);
break;
}
while (in.hasNextLine()) {
String line = in.nextLine();
if (!line.matches("..*" + separator + "..*")) continue;
int index = line.indexOf(separator);
String question = line.substring(0, index);
String answer = line.substring(index + separator.length());
index = answer.indexOf(separator);
if (index != -1)
answer = answer.substring(0, index);
if (answer.isEmpty()) continue;
list.add(new TestItem(question, answer));
System.err.println(question + " :: " + answer);
}
in.close();
} catch (FileNotFoundException | InputMismatchException e) {
e.printStackTrace();
}
return list;
}
}