2011-02-23 61 views
1

我有一张表,其中包含一些我需要整合到Java程序中的因素。起初我正在考虑对这个数字进行硬编码,但是试图创建一个适合这些因素的数据结构似乎是一种痛苦。所以我想问一下,看看在数据库,平面文件或java中实现这个参考数据会更好。这个数字每六个月会改变一次,并用于数学计算。如何实现参考数据Java /数据库

想法?

Factor List

回答

1

你将不得不创建一个数据结构来存储数据,无论你如何保存它们。但是这种数据的数据结构并不复杂。它只是一个具有属性值的列表。您不必将它们存储在复杂的表格式结构中。

表示数据作为一个单独的列表加载时,从一个纯文本文件中的数据也将是相当容易的。

public class DataTable { 

    private List<Entry> table = new ArrayList<Entry>(); 

    public double getValue(Sex sex, MaritalStatus maritalStatus, AgeInterval ageInterval, Type type) { 
     for (Entry entry : table) { 
      if (entry.sex == sex && entry.maritalStatus == maritalStatus && entry.ageInterval == ageInterval && entry.type == type) { 
       return entry.value; 
      } 
     } 
     throw new IllegalArgumentException("Unknown value"); 
    } 

    public void load(String filename) { 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       StringTokenizer t = new StringTokenizer(line, ":"); 
       table.add(new Entry(
         Sex.valueOf(t.nextToken()), 
         MaritalStatus.valueOf(t.nextToken()), 
         AgeInterval.valueOf(t.nextToken()), 
         Type.valueOf(t.nextToken()), 
         Double.valueOf(t.nextToken()))); 
      } 
     } catch (IOException e) { 
      throw new IllegalStateException("Failed to read the data file", e); 
     } 
    } 

} 

enum Sex {M, F} 
enum MaritalStatus {SINGLE, MARRIED} 
enum AgeInterval {I16_21, I22_35, I35_55, I55} 
enum Type {GD, NGD} // Whatever this is ... 

class Entry { 
    Sex sex; 
    MaritalStatus maritalStatus; 
    AgeInterval ageInterval; 
    Type type; 
    double value; 

    Entry(Sex sex, MaritalStatus maritalStatus, AgeInterval ageInterval, Type type, double value) { 
     this.sex = sex; 
     this.maritalStatus = maritalStatus; 
     this.ageInterval = ageInterval; 
     this.type = type; 
     this.value = value; 
    } 
} 

数据文件应该是这样的:

M:SINGLE:I16_21:GD:1.10 
F:SINGLE:I16_21:GD:1.20 
... 
3

对于这样的缓慢变化的数据,我会使用外部配置文件。根据您的数据结构,似乎CSV可以很好地工作,并且对于商业用户而言,使用Excel进行编辑很容易。

如果它会更频繁地更换,你需要以编程方式生成数据,或者你想编辑的数据提供了一个用户界面,你可以将它移动到数据库中。

0

您可以分解字段的一种方式是性别,年龄,婚姻状况,GD_VS_NGD,表格中的数据以及您使用此数据的时间段的一些标识符,除非您不需要保存记录的数据。

1

你可以把它表示XML,但可能是这样的数字数据有点沉重。但是XML可以让你具有相当的描述性和自我记录。之后,您可以轻松地将其解析为Java(或您选择的其他语言)。

部分XML例如:

<dataset> 
    <gd> 
    <16to21> 
     <single> 
     <male>1.10</male> 
     <female>1.20</female> 
     </single> 
     <married> 
     <male>0.90</male> 
     <female>0.80</female> 
     </married> 
    </16to21> 
    ... 
    </gd> 
    <ngd> 
    ... 
    </ngd>