java - 如何解决有关变量的以下问题?
问题描述
我有一个类,里面有一个 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 变量。我怎样才能使它可访问?
解决方案
与其在函数内部创建一个新变量,不如在函数外部创建一个公共变量。
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();
}
推荐阅读
- regex - 根据特定单词选择句子
- php - 从虚拟主机上的 Nginx 配置中的请求中检测 URL 查询参数
- typescript - 如何获得键值的联合,并保留联合值
- python - JSON加载中错误值的错误处理
- usb - 仅 STM32 USB OTG 设备 - 除非也插入编程 USB 端口,否则无法检测到?
- flutter - Provider - Selector rebuild when scrolling
- python - discord.Guild.get_member() 在未绑定的方法调用 discord.py 中参数“self”没有值
- python - 从 Python 访问 WRDS:无连接
- openmesh - OpenMesh 将所有标准和自定义属性从一个网格元素复制到另一个网格元素
- reactjs - 尝试使用来自 node.js 服务器的 React useEffect 和 useState 加载图像的动态路径