繁体   English   中英

如何将字符串存储到哈希图中没有名称的新String []中?

[英]How do I store a string into a new String[] that has no name in a hashmap?

我正在做一个问与答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();
            }  
        }
    }
}

您可以通过多种方式执行此操作。 使用数组初始化语法,您可以在一行中完成此操作:

Questions.put(a, new String[]{input.nextLine(),
    input.nextLine(),
    input.nextLine()});

但这当然提出了一个问题,我们怎么知道总是会有三行可用,并且它们都将与同一密钥相关联? 可能会有更多或更少吗? 这些考虑因素可能会导致一种更健壮和灵活的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM