首页 > 解决方案 > 如何解决有关变量的以下问题?

问题描述

我有一个类,里面有一个 baseDir 变量,定义如下:

public class experiment {
    for (int exp = 0; exp < experimentCnt; exp++) {
        String dirString = config.getClass().getSimpleName() + "_" + df.format(new Date());
        String baseDir = new File(homeDir + "/" + dirString).getAbsolutePath();
        System.out.println("Running simulation: " + dirString);

        setCurrentDirectory(baseDir);

        PrintWriter paramsLog = null;

        try {
            paramsLog = new PrintWriter(
                 new File("experimentParams.log").getAbsoluteFile(), "UTF-8");
            paramsLog.println(params);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

现在,我想在另一个类中使用那个 baseDir 变量。我怎样才能使它可访问?

标签: javacloudsim

解决方案


与其在函数内部创建一个新变量,不如在函数外部创建一个公共变量。

public class experiment {

public String baseDir;

    for (int exp = 0; exp < experimentCnt; exp++) {
        String dirString = config.getClass().getSimpleName() + "_" + df.format(new Date());
        baseDir = new File(homeDir + "/" + dirString).getAbsolutePath();
        System.out.println("Running simulation: " + dirString);

        setCurrentDirectory(baseDir);

        PrintWriter paramsLog = null;

        try {
            paramsLog = new PrintWriter(
                 new File("experimentParams.log").getAbsoluteFile(), "UTF-8");
            paramsLog.println(params);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

推荐阅读