gpt4 book ai didi

java - 在 Robocode (Java) 中写入文件

转载 作者:行者123 更新时间:2023-12-04 14:42:41 30 4
gpt4 key购买 nike

基本上,我试图在 Robocode 中生成一个日志文件,但我遇到了问题,因为您不能在 Robocode 中使用 try/catch(据我所知)。我做了以下事情:

public void onBattleEnded(BattleEndedEvent e) throws IOException
{
writeToLog();
throw new IOException();
}

public void writeToLog() throws IOException
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new IOException();
}

并且在编译时出现以下错误:-

MyRobot.java:123: onBattleEnded(robocode.BattleEndedEvent) in ma001jh.MyRobot cannot implement onBattleEnded(robocode.BattleEndedEvent) in robocode.robotinterfaces.IBasicEvents2; overridden method does not throw java.io.IOException
public void onBattleEnded(BattleEndedEvent e) throws IOException
^
1 error

最佳答案

如你所见here ,该接口(interface)不声明任何已检查的异常。所以你不能在你的实现类中添加一个。

解决这个问题的一种方法是像这样实现您的方法:

public void onBattleEnded(BattleEndedEvent e)
{
writeToLog();
throw new RuntimeException(new IOException());
}

public void writeToLog()
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new new RuntimeException(new IOException());
}

关于java - 在 Robocode (Java) 中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5204304/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com