1
我正在做一個Q和一個AI類型的東西,並試圖將其數據保存到一個txt文件,以便它保留上次會話的問題,有點像cleverbot。有沒有更簡單的方法來做到這一點?或者有什麼方法可以將字符串存儲到新的String []中?如何將一個字符串存儲到一個在hashmap中沒有名字的新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();
}
}
}
}
我只對每個問題做三行,謝謝。 –