我正在做一个Q和A AI类型的事情,并且我正在尝试将其数据保存到txt文件中,以便它保留上一个会话中的问题,有点像cleverbot。有更简单的方法吗?或者有没有办法将字符串存储到新的String []?
import java.lang.Math.*;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class QandA{
public static void main(String[] args)throws Exception{
String UE, OUE, a;
int i;
String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
Map<String, String[]> Questions = new HashMap<>();
Questions.put("Why", Why);
Scanner k = new Scanner(System.in);
File f = new File("QandA_Data.txt");
while (true){
if (f.exists() && f.length() > 0){
Scanner input = new Scanner(f);
for (int c = 0; c < f.length(); c++){
a = input.nextLine();
Questions.put(a, new String[3]);//<====// This new string
for (int v = 0; v < 3; v++){ //
a = input.nextLine(); //
//I want to store a value here into//
}
}
}
System.out.println(" Ask a question! ");
UE = k.nextLine();
if(Questions.keySet().stream().filter(UE::equalsIgnoreCase).findFirst().isPresent()) {
i = (int) Math.floor(Math.random()*3);
System.out.println(Questions.get(UE)[i]);
} else {
System.out.println(" Question Not Found. Enter 3 answers to the question: ");
OUE = k.nextLine();
Questions.put(UE, new String[3]);
Questions.get(UE)[0] = OUE;
OUE = k.nextLine();
Questions.get(UE)[1] = OUE;
OUE = k.nextLine();
Questions.get(UE)[2] = OUE;
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
for (int c = 1; c < Questions.size(); c++) {
out.println(UE);
for (int v = 0; v < Questions.get(UE)[c].length(); v++){
out.println(Questions.get(UE)[c]);
}
}
out.close();
}
}
}
}
答案 0 :(得分:2)
有很多方法可以做到这一点。以下是使用数组初始化语法在一行中完成的方法:
Questions.put(a, new String[]{input.nextLine(),
input.nextLine(),
input.nextLine()});
但这当然提出了一个问题,我们怎么知道总有三条线可用,而且它们都与这个相同的键相关联?可能会有更多或更少?这些考虑可能会导致更加强大和灵活的方法。