Pratswinz
Pratswinz

Reputation: 1476

Getting syntax error on token "," , {expected after this token

I know there are already similar questions here but i tried the solutions but none worked,so i providing my code and java build path configurations settings ,so kindly help.i am using java 1.8

import java.io.File;
import java.util.ArrayList;
import java.util.List;




public class Pics {
    List<String> results = new ArrayList<String>();


    File[] files = new File("/path/to/the/directory").listFiles();
    //If this pathname does not denote a directory, then listFiles() returns null. 

    for (File file : files) {
        if (file.isFile()) {
            results.add(file.getName());
        }
    }
}

I am attaching the snapshot of the error,even though the curly braces are balanced but it still show error to insert "}" to complete class bodyerrors![][1]

build config

Upvotes: 3

Views: 1187

Answers (2)

Ayush
Ayush

Reputation: 311

In Java, only the declarations of variables can be written directly in class but in case you want to write some logic, use the functions. This is what the definition of class says: wrapper for data and functions that act on that data. Additionally use constructors to provide wrapper to initializations.

import java.io.File;
import java.util.ArrayList;
import java.utilList;

public class Pics {
    List<String> results;
    File[] files = null;
    public Pics() {
        results = new ArrayList<String>();
        files = new File("/path/to/the/directory").listFiles();
    }

    //If this pathname does not denote a directory, then listFiles() returns null. 
    public void testFunction() {
        for (File file : files) {
            if (file.isFile()) {
                results.add(file.getName());
            }
        }
    }
}

Upvotes: 1

Eran
Eran

Reputation: 393781

This for loop must be inside some method :

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

Upvotes: 1

Related Questions