开发者

Call String from one method to another in Java

sorry if this is 开发者_如何转开发a simple question but I have been trying for quite a while now is it possible to call a string from one method to another...

Below I want to call the string fileName from the method fileName to fileOutputToFile. I know I can pass it in but I want to call it from fileOutputToFile.

public class outputToFile {

    public void fileName(){

         String fileName = "Test";

    }

    public void fileOutputToFile(String hex) throws Exception{

        String fileInfo = hex;

        try {
                PrintWriter out = new PrintWriter(new BufferedWriter(
                                         new FileWriter("myfile.txt", true)));
                out.print(fileInfo);
                out.print("\n");
                out.close();
            }catch (IOException e){
            }
    }
}


It's not possible to call a local variable which is in another method -- it's an issue of scope.

Therefore, it is not possible to retrieve the fileName variable from the fileName() method from the fileOutputToFile method.

One way to "retrieve" the file name would be to return the file name when the fileName method is called:

public String getFileName(){
     String fileName = "Test";
     return fileName;
}

(Note: I've taken the liberty to rename the method to something that would be closer to the conventions for naming identifiers in Java.)

Then, in the fileOutputToFile method, the getFileName method can be called to retrieve the value of the fileName.


It should be noted that in this case, it may actually be better to just use an field (an instance or class variable) rather than calling a separate method to retrieve a file name. Considering the method is just returning a constant String, a field could hold the value:

public class OutputToFile {
    // Here, we use a class variable.
    private static final String FILE_NAME = "Test";

    public void fileOutputToFile(String hex) {
        // use FILE_NAME field here.
    }
}


All variables have scope that is generally limited to the {} enclosure that they are in. So, if you create a variable in one method, it is not accessible in another method unless you pass it in.

The good news is you can create class level variables that are shared by all methods within a class!

public class OutputToFile {

    private String fileName = "Test";

    public void fileName() {
           System.out.println(fileName);
           fileName = "Something Different"
    }

    public void fileOutputToFile(String hex) {
           System.out.println(fileName);
           // Do other things with it
    }
}


If I understand you correctly, you wish to return a string from fileName().

Currently, your implementation of fileName() does nothing. You must add a return statement to return a value: 'return "Test"'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜