代码之家  ›  专栏  ›  技术社区  ›  Bad Request

在这种情况下,保存响应集的更好方法是什么?

  •  1
  • Bad Request  · 技术社区  · 14 年前

    我正在用Java构建一个CLI调查应用程序,让用户回答多项选择题。请告诉我如何改进我的方法。

    每个问题的答案都记录为int,它是该问题的选项数组中该选项的索引。调查的所有答案都保存为int数组。我正在考虑使用ObjectOutputStream对这个int数组进行序列化。然后当我需要显示结果时,我将恢复数组并在一个选项卡后打印每个元素。

    这种方法的问题在于(我相信)第二组响应覆盖了第一组响应。我想到了两个选择,两个听起来都很糟糕。一个是将每个响应集保存到单独的文件中。但是到了显示时间,我必须一次读取所有文件,以将同一问题的响应放在一起。另一种方法是将int数组保存为纯文本文件中以制表符分隔的行(因此每个响应集都会生成一行新行),然后标记化并将其解析回int数组进行显示。但是,标记化/解析代码是一种恐怖的阅读方式(目前看起来是这样的):

    编辑:哎呀,这个代码都不对。我的观点是解析是一团糟,所以我在寻找一种不必解析的方法。

    File savedResults = new File(Main.surveyResultsFolder, surveyFileName);
    try {
        BufferedReader br = new BufferedReader(new FileReader(savedResults));
        int[] currentResponseSet = new int[noOfQuestions];
        String currentResponseString = "";
        String[] currentResponseStrArray = null;
        while((currentResponseString = br.readLine()) != null) {
            currentResponseStrArray = currentResponseString.split("\t");
    
        for (int i = 0; i < currentResponseStrArray.length; i++) {
            currentResponseSet[i] = Integer.parseInt(currentResponseStrArray[i]);
    }
        }
         //then I'll print currentResponseSet here.
        }
    catch (IOException ex) {
        System.out.println("Error reading results file " + surveyFileName);
    }
    

    我没主意了。如您所见,我对数据处理技术的了解是有限的。有接受者吗?

    2 回复  |  直到 9 年前
        1
  •  1
  •   Dilum Ranatunga    14 年前

    1. Map<record, Map<question, answer>>
        public abstract class AutoMap<K extends Comparable, V> 
        extends TreeMap<K, V> {
          protected abstract V createValue();
    
          public V getOrCreate(K key) {
            V value = get(key);
            if (value == null) {
              value = createValue();
              put(key, value);
            }
            return value;
          }
        }
    
        public class MapOfMaps<J extends Comparable, K extends Comparable, V> 
        extends AutoMap<J, Map<K, V>> {
          protected Map<K, V> createValue() {
            return new TreeMap<K, V>();
          }
        }
    
        2
  •  3
  •   Jay    14 年前