我正在尝试完成一份旧的实验室工作表,以修改一些 java 代码,因为我忘记了如何编写(我对编码相当陌生)。在代码的一个部分中,我必须读入(作为 Double 的 ArrayList)已提供的文本文件,其中包含前 1000 个素数。所以我目前有一个基本的方法,需要进行调整才能使其有效地发挥作用。我还将权重作为健身函数问题的一部分。
然后,我必须使用 (8) 个质数生成尺度问题的多个随机解决方案。
因此,我需要在适当的位置编辑下面的代码才能读取文件。
感谢您的帮助:D!
static public ArrayList<Double> ReadNumberFile(String filename) {
ArrayList<Double> res = new ArrayList<Double>();
Reader r;
try {
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER) {
res.add(stok.nval);
}
stok.nextToken();
}
} catch (Exception E) {
System.out.println("+++ReadFile: " + E.getMessage());
}
return (res);
}
最佳答案
读取数字的方式取决于给定文件的格式,最重要的是,素数的分隔方式(即将一个素数与下一个素数分隔开的字符)。从这里开始,我假设它们是在浸出线上带有一个素数的。
File file = new File("primes.txt"); // get a file object referring to the list of primes
List<String> lines = Files.readAllLines(file.toPath()); // read all the lines, and store them in a List<String>
List<Double> primes = new ArrayList<>(); // initialize an empty list to put the primes
for (int i = 0; i < lines.length(); i++) { // iterate over the lines
primes.add(Double.parseDouble(lines.get(i))); // convert each line into a double and add to the list
}
几点:
- 素数都是整数,这里应该使用
int
。 - 只需使用以下内容即可使其变得更短(尽管不太容易向初学者解释):
List<Integer> primes = Files.lines(new File("primes.txt").getPath())
.map(Integer::parseInt)
.collect(Collectors.asList());
- 此实现对于输入格式来说非常脆弱,如果它们没有按照我的假设方式提供给您,则需要进行修改。例如,如果它们以逗号分隔,则必须将它们读入
String
,然后使用string.split(",")
获取值数组.
关于java - 读入1000个素数文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57540564/