Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 605
Pratswinz Avatar asked Apr 25 '26 14:04

Pratswinz


2 Answers

This for loop must be inside some method :

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}
like image 79
Eran Avatar answered Apr 28 '26 05:04

Eran


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());
            }
        }
    }
}
like image 35
Ayush Avatar answered Apr 28 '26 03:04

Ayush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!