cohara
cohara

Reputation: 111

Java write to .csv file

I am trying to write to a .csv file, but I keep getting the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    void is an invalid type for the variable writeToFile
    Syntax error on token "(", ; expected
    Syntax error on token ")", ; expected

The error is associated with the line:

void writeToFile(String Filename){

Here is my code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileWriter;

public class writeFileExample {
    public static void main(String[] args) {
        void writeToFile(String Filename){
            double steps=0;
            File file=new File(Filename);
            file.createNewFile();
            FileWriter writer=new FileWriter(file);
            try {
                //Integrate integrate=new Integrate();
                //for (steps=10;steps<1000000;steps=steps*10){
                    //double area_value=integrate.integrate_function(steps);
                    writer.write("Steps"+","+"Area");
                    //}
                //System.out.println(area_value);
                writer.flush();
                writer.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }
}

I can't see any syntax errors.

Taking into account Reimeus' comment below I edited it a bit. I now have:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileWriter;

void writeToFile(String Filename){
public class writeFileExample {
    public static void main(String[] args) {
            double steps=0;

etc.

I am getting the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Filename cannot be resolved to a variable

Any help appreciated.

Upvotes: 1

Views: 1318

Answers (2)

ferrariturbo
ferrariturbo

Reputation: 1

public class Test {
    public static void main(String[] args) {
    try {
        writeToFile("c:\\abc.csv");
    } catch (IOException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }
    static public void writeToFile(String Filename) throws IOException 
    {
      .
      .
      .
      .
    }
}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159844

Java doesnt support nested methods. Move writeToFile out of the main method

Upvotes: 3

Related Questions