好吧,我正在开发一个读取元素周期表的程序,您可以根据数字或缩写搜索元素。
无论如何,我在尝试将元素周期表文件读入 4 个不同的数组时遇到了一些困难:原子序数、缩写、元素名称和原子量。
我不知道如何编写一个方法来一次性将所有这些信息导入到每个数组中。我想要一个类来保存所有这些数组,并且我可以在以后需要每个数组时调用它。
这是我到目前为止所得到的,顺便说一句,我有点生疏了......我认为开发这个程序会让我重新熟悉基础知识。
class PeriodicTable{
private String fileName = "periodictable.dat";
private int[] atomicNumTable = new int[200];
private String[] abbreviationTable = new String[200];
private String[] nameTable = new String[200];
private double[] atomicWeightTable = new double[200];
PeriodicTable(String fileName){
readTable(fileName);
}
public int[] readTable(String fileName){
Scanner inFile = null;
try{
inFile = new Scanner(new File(fileName));
}catch(FileNotFoundException nf){
System.out.println(fileName + " not found");
System.exit(0);
}
atomicNumTable = new int[200];
int i = 0;
while(inFile.hasNext() && i < atomicNumTable.length){
int number = inFile.nextInt();
atomicNumTable[i] = number;
i++;
}
inFile.close();
return atomicNumTable;
}
}
表格的每一行如下所示:
1 H Hydrogen 1.00794
最佳答案
- 只需使用 java.lang.String.split(' ') (假设您的列使用空格分隔;如果使用其他内容;您只需调整正则表达式参数即可!)
- 这将返回一个字符串数组;现在基本上:第一列应该是一个 int,然后你有两个字符串,然后是一个 double 值。或者更准确地说:您得到的字符串意味着其他东西;因此你必须研究像 Integer.valueOf() 这样的方法; Double 也类似。
从那里开始工作应该不会太难。
但我建议对您的逻辑进行一些更改:拥有 4 个不同的表根本没有意义。好的面向对象编程就是创建有用的抽象。如果没有抽象,您的程序本身就会变得抽象。
含义:你应该引入一个类似的类
public class Element {
private final int id;
private final String abbreviation;
private final String fullName;
private final double atomicWeight;
... with one constructor that takes all 4 parameters
... with getter methods for the fields of this class
... and meaningful overrides for equals() and hashcode()
}
然后,不再创建 4 个数组;您创建一个数组,或者更好的是 ArrayList<Element>
。您无需将 4 个值插入 4 个不同的数组,而是在每次循环迭代中创建一个新的 Element 对象;然后您将该新对象添加到您的列表中。
您的解决方案的主要区别在于:您可以将 Elements 作为一个整体进行处理;而在您的解决方案中,单个“元素”基本上是一个指向 4 个不同表的索引。
关于java - 如何将 .dat 文件导入到多个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39444191/