0

I am trying to return the value of the method but the loop is throwing an error because the return has to be in the method body not in the loop. I am using system.out.println and it is works but I want to use return instead.

package AnimeAid;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ReadFile {


    public void getFileInformation() throws IOException {   
        try{
            String file;
            file = "tra.srt";
            Charset charset = Charset.defaultCharset();
            Path path = Paths.get(file);
            BufferedReader reader = Files.newBufferedReader(path, charset);
            System.out.printf("Lines from %s:%n",file);
            String line;

            while((line = reader.readLine()) != null) {
                if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) { 
                    System.out.println(line.substring(0, 12)); 
                }
            }
        }catch(FileNotFoundException ex){
            System.err.println(ex);
        }

    }
}
4
  • please describe what you are trying to do with this code. Commented Feb 8, 2014 at 8:09
  • ok i will give me some time Commented Feb 8, 2014 at 8:12
  • you can take a look i changed it all Commented Feb 8, 2014 at 8:53
  • 1
    A return statement can be in a loop (of course it will be executed at most once). The problem here seems to be that the method is declared as void. Commented Feb 8, 2014 at 9:00

1 Answer 1

1

You can obviously return from the for loop.

public String getFileInformation() throws IOException {   
 try{
    String file;
    file = "tra.srt";
    Charset charset = Charset.defaultCharset();
    Path path = Paths.get(file);
    BufferedReader reader = Files.newBufferedReader(path, charset);
    System.out.printf("Lines from %s:%n",file);
    String line;

    while((line = reader.readLine()) != null) {
    if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) { 
    return line.substring(0, 12); 
    }
    }
    }catch(FileNotFoundException ex){
    System.err.println(ex);
    }

    return "";
}
Sign up to request clarification or add additional context in comments.

4 Comments

return are not used for printing right ? so nothing going to show up ?
but you said you want to return value?
that is right i set your answer as right answer but i am asking about return function
Sorry but i didn't get you. Can you please say clearly what you actually want? Then I may help you further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.