seiryuu10
seiryuu10

Reputation: 903

Writing a string and 2D Array to a .txt file - Java

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());
        }
  }

Upvotes: 0

Views: 2576

Answers (2)

k-den
k-den

Reputation: 853

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?

Upvotes: 1

Attila
Attila

Reputation: 28772

Scanner is used to read from a file/stream, but you want to output to the file. Use one of the Writer classes (e.g. FileWriter, possibly coupled with BufferedWriter) instead

Upvotes: 0

Related Questions