我有一个类,里面有一个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变量。如何使其可访问?
答案 0 :(得分:-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();
}