i有一个.txt文件,其中包含300行和785列,其中包含一堆数字(例如-6.431571950262252035E -02)。我将如何将这些数字掩盖到2D数组中?
这就是我所拥有的:
double[][] hiddenArray = new double[300][785];
Scanner scanner = new Scanner(System.in) ;
String hiddenFile = "hidden-weights.txt";
String outputFile = "output-weights.txt";
scanner.close();
Scanner in = new Scanner(new File(hiddenFile));
String hidden= in.nextLine();
使用scanner :: hasnext()循环循环,而有更多行和scanner :: nextline()获取下一行,然后使用string :: split()获取数组每条线上的字符串(注意:我的推测是列是通过逗号分隔的(即,
),但可以随意调整您的需求)。要在e符号中解析数字,请使用double.valueof(),然后将该值添加到数组(例如 hiddenarray )。
您应该能够使用以下样本。我还在tutorialspoint.com编码地上创建了一个示例,但这可能不起作用...
try {
String delimiter = ","; //separates columns - change for your needs
int row = 0;
Scanner in = new Scanner(new File(hiddenFile));
String line;
while (in.hasNext() && (line = in.nextLine()) != null ) {
String[] vals = line.trim().split(",");
for (int col = 0; col < vals.length; col++) {
hiddenArray[row][col] = Double.valueOf(vals[col]);
}
row++;
}
}
catch(FileNotFoundException e) {
System.out.println("file not found - "+e.getMessage());
}