【问题标题】:Identifier expected error when calling a method in java在 java 中调用方法时出现标识符预期错误
【发布时间】:2014-03-12 07:26:05
【问题描述】:

我有这个用java 编写的相当简单的代码。这实际上来自一个 DAQ 框架,称为 Kmax

import kmax.ext.*; 

public class Runtime implements KmaxRuntime {
    KmaxToolsheet tlsh; // Store a reference to the toolsheet environment
    KmaxHist hist1D;
    KmaxWidget checkBoxWidget;

    public void init(KmaxToolsheet toolsheet) {
        tlsh = toolsheet; // Save this reference for use in the toolsheet
        hist1D = tlsh.getKmaxHist("HIST1D");
        checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
        tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH").setProperty("VALUE", "1");

    }

    public void CalibInit(KmaxWidget widget, KmaxHist histo){
        histo.setUseXAxisCalibration(stringToBool(widget.getProperty("VALUE")));
        histo.update();

    }
    CalibInit(checkboxWidget,hist1D);

    public void GO(KmaxToolsheet toolsheet){}
    public void SRQ(KmaxDevice device) {}
    public void HALT(KmaxToolsheet toolsheet) {}

} // End of the Runtime object

请注意,我在那里创建了一个名为 CHECK_BOX_CALIB_METH 的对象。当我编译这段代码时,我会收到这些错误消息

compiler msg>error: invalid method declaration; return type required
compiler msg>   CalibInit(checkboxWidget,hist1D);
compiler msg>   ^

compiler msg>error: <identifier> expected
compiler msg>CalibInit(checkboxWidget,hist1D);
compiler msg>                        ^


compiler msg>error: <identifier> expected
compiler msg>CalibInit(checkboxWidget,hist1D);
compiler msg>                               ^

请注意,如果我删除 CalibInit 方法并将其替换为

public void CHECK_BOX_CALIB_METH(KmaxWidget widget) {

    hist1D.setUseXAxisCalibration(stringToBool(widget.getProperty("VALUE")));
    hist1D.update();

}

我没有编译错误。关键是方法的名称与对象的名称相同。我创建CalibInit() 的原因是为了避免为每个具有相同功能的相同类型的对象使用每个方法。有办法解决吗?

如何避免这些错误?

【问题讨论】:

    标签: java compiler-errors return identifier


    【解决方案1】:

    代码

    CalibInit(checkboxWidget,hist1D); 
    

    独立的一行不在你的任何方法中。编译器假定这是一个可能不是您想要的新方法声明。

    旁注:
    不建议方法以大写字符开头:“方法应该是动词,大小写混合,首字母小写,每个内部单词的首字母大写。”来自Code Conventions for the Java Programming Language

    【讨论】:

    • 非常感谢您的帮助!
    【解决方案2】:

    您在类中直接调用 CalibInit(checkboxWidget,hist1D) 方法,而不是在任何方法中。 Java 不支持这个。

    【讨论】:

      【解决方案3】:

      你不能打电话

      CalibInit(checkboxWidget,hist1D);
      

      像你一样直接在课堂上。如果您的目标是在构造运行时实例时调用该指令,则该指令应位于构造函数中。

      顺便说一句:在 Java 中,方法以小写字母开头,您不应该调用您的类 Runtime:它会混淆人们,因为标准库中已经存在标准 Runtime 类。

      【讨论】:

      • 非常感谢您的帮助和建议!我是java新手,所以我会尽力学习它!再次感谢!
      【解决方案4】:

      只有变量可以在方法之外声明。您只能在方法和构造函数中调用方法(在此避免静态上下文)。

        CalibInit(checkboxWidget,hist1D);
      

      如果需要,请将该行移至任何方法或构造函数。更具体地说,在您需要的地方打电话。

      简而言之: CalibInit(checkboxWidget,hist1D); 现在是孤儿。让它属于某物。

      【讨论】:

      • 非常感谢您的宝贵时间和帮助!
      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2017-06-25
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多