问题描述
我正在尝试将单个字符串和2D数组输出到.txt文件中并遇到问题,这是我项目的最后一部分。该程序应该输出一行,逗号分隔,字符串,然后在下一行,打印出2D数组中的双打,逗号分隔。我想能够将此全部打印到.txt文件,然后在excel文件中打开该.txt文件以绘制信息图形。以下是我到目前为止所知道的错误可能比我看到的更多:
public void writeFile(double [ ] [] array,String filename)
{
try {
File f = new File(output.txt);
扫描仪扫描=新扫描仪(f);
scan.useDelimiter(\\\\ *,\\ t *);
String label =Algoritm-1,Algorithm-2,Algorithm-3,
+n,n-squared,n-cubed; //只有一行打印此行
for(int i = 0; i< = 18; i ++)
{
for(int j = 0; j< = 5; j ++)
{
array [i] [j] = scan.nextDouble(); //当前发行
}
scan.nextLine();
}
}
catch(FileNotFoundException fnf){
System.out.println(fnf.getMessage());
}
}
它看起来你在输出文件上使用扫描仪。扫描仪通常用于读取输入文件。打开一个新的输出文件并将该数组打印到该文件。
查找OutputStreamWriter的示例。这里有一个:
建议:您可以使用数组维度的长度来代替使用18和5作为循环吗? / p>
I am trying to output a single string and 2D array into a .txt file and am running into issues and this is the last part of my project. The program should output a single line, comma-delimited, String, then on the next line, prints out the doubles within the 2D array, comma-delimited. I am suppose to be able to print this all to the .txt file and then open that .txt file in a excel file to graph the information. Here is what I have thus far and I understand there may be more errors than I may see:
public void writeFile(double[][] array, String filename)
{
try{
File f = new File("output.txt");
Scanner scan = new Scanner(f);
scan.useDelimiter("\\s*,\\s*");
String label = "Algoritm-1, Algorithm-2, Algorithm-3, "
+ "n, n-squared, n-cubed"; //Only one printing of this line
for (int i = 0; i <= 18; i++)
{
for (int j = 0; j <= 5; j++)
{
array[i][j] = scan.nextDouble(); //Having the current issue
}
scan.nextLine();
}
}
catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
}
It looks like you are using a scanner on your output file. The scanner is generally used to read input files. Open a new output file and print the array to that file.
Look for an example of OutputStreamWriter. There's one here:http://www.javapractices.com/topic/TopicAction.do?Id=42
Suggestion: Instead of using 18 and 5 for your loops, can you use the lengths of the array dimensions?
这篇关于将字符串和2D数组写入.txt文件 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!