【问题标题】:How can I fix the following problem regarding the variable?如何解决有关变量的以下问题?
【发布时间】:2019-11-01 08:42:03
【问题描述】:

我有一个类,里面有一个 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 变量。如何使其可访问?

【问题讨论】:

  • 你不能在类中直接使用 for 循环。

标签: java cloudsim


【解决方案1】:

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

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();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2021-08-19
    • 2021-03-04
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多