Java 将类从类发送到主类

Java 将类从类发送到主类,java,class,object,methods,ioexception,Java,Class,Object,Methods,Ioexception,我的代码目前设置为有3个类文件,main和tradeShip。tradeShip已经收到另一个类文件,playerShip。在贸易船代码中,我需要将玩家送回main。代码如下: public class tradeShip() { public void sell(playerShip player) { //unimportant code main.saveGame(player); } } public class main() { public void

我的代码目前设置为有3个类文件,main和tradeShip。tradeShip已经收到另一个类文件,playerShip。在贸易船代码中,我需要将玩家送回main。代码如下:

public class tradeShip() {
  public void sell(playerShip player) {
    //unimportant code
    main.saveGame(player);
  }
}


public class main() {
  public void saveGame (playerShip player) throws IOException {
    //code that deals with writing to text files
  }
}
然而,这在main.saveGame(player)中给了我一个错误;其中显示“未报告的异常IOException;必须捕获或声明要抛出”

我不确定到底发生了什么,任何帮助都将不胜感激

saveGame抛出ecxeption(错误) 您必须捕获并处理它:

try {
    main.saveGame(player); // throw exception
} catch (IOException e) {
    //some error processing
    e.printStackTrace();
}
或者声明sell也会抛出它,以便在更高级别捕获和处理它

 public void sell(playerShip player) throws IOException {

在saveGame方法的签名中,您正在抛出一个IOException,该IOException未在该方法的主体中引发。因此,您可能必须删除它,因为您可能已经在任何catch子句中管理了它


此外,我想澄清一下。。。所有类名都必须大写(这是java编程的一个好规则),并且您所讨论的方法不会接收java类,而只是该对象类型的一个实例

对于初学者,去掉类声明中的(),您需要阅读检查过的异常。这不能是您的实际代码。。。类的声明中没有括号。至于您的实际问题,您的
saveGame
方法声明它可以抛出
IOException
。因为这是一个选中的异常,所以无论您在哪里调用
saveGame
都需要提供一个try-catch块来处理错误,或者还需要声明它在方法签名中抛出相同的异常。按照约定,类名也以大写开头。