【问题标题】:Getting "cannot find symbol" error while using static methods使用静态方法时出现“找不到符号”错误
【发布时间】:2014-09-28 18:51:41
【问题描述】:

我有非常简单的代码,我已经删除了奇数代码。

所以这是我的课,他的方法之一是静态的,我想稍后在Main class 中使用它:

public  class  TradeInformationReader {

 private static String tradeType = "FX_SPOT";
 public static double tradePrice = -1;
 private double price;

 public  static int setTradeInformation(String path_to_file) {
 return 1;
  }
 }

这里是我如何尝试调用最后一个方法:

public class Main {

public static int main(String[] args) {

    String path_to_file = "D:\\1.txt";
    if (0 > TradeInformationReader.setTradeInformation(path_to_file)) {
        return -1;
    }

    return 1;
 }
}

我阅读了许多类似问题的帖子,但找不到解决方案。在我看来一切都很好。 IDE 没有显示任何错误,我只是尝试调用静态方法setTradeInformation,为什么它无法识别它(找不到符号方法setTradeInformation)?有任何想法吗?非常感谢您的帮助。

【问题讨论】:

  • 无法识别的符号是什么?
  • 为什么setTradeInformation总是返回1?
  • @Kick Buttowski 我认为这只是一个例子......他知道如果实现真的是那样,它永远不会进入第二个 IF 条件。
  • TradeInformationReader 是内部类吗? (未在其自己的文件中定义)
  • @NicolasAlbert 我调用静态方法

标签: java static-methods


【解决方案1】:

您的 main 不是有效的 main,所以我猜您的 IDE 找不到启动类。这应该是

public static void main(String[] args)

【讨论】:

  • @Dice 真奇怪,现在可以了,为什么使用 void 这么重要?
  • @Rocketq 这就是你定义迷你应用“入口点”的方式。
  • 阿尔博兹是这么说的!请注意,在 C 和 C++ 中,main 返回一个 int。
【解决方案2】:

首先,您必须将 TradeInformationReader 类放在一个名为 TradeInformationReader.java 的单独文件中

如下:`

public  class  TradeInformationReader {

 private static String tradeType = "FX_SPOT";
 public static double tradePrice = -1;
 private double price;

 public  static int setTradeInformation(String path_to_file) {

    //integer to identify whether the file is found or not 1 if found and 0 if not
    int isFileFound = 1;

    // the code required to get the file and modify the state of the of isFileFound variable

    return isFileFound;
  }
 }

`

那么主类应该有 void 返回类型,并且应该在一个与主类同名的文件中,如下所示:

 public class firstApp {

 public static void main(String[] args) {

String path_to_file = "D:\\1.txt";
if (0 > TradeInformationReader.setTradeInformation(path_to_file)) {
    System.out.println("File not found");
}

} } `

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    相关资源
    最近更新 更多