【问题标题】:Java using a method public int instead of public static int [duplicate]Java使用方法public int而不是public static int [重复]
【发布时间】:2016-06-19 05:34:52
【问题描述】:

我想使用“public int CountWord”而不是“public static int CountWord”,下面的代码给了我错误,Cannot make a static从类型 CountWord 引用非静态方法 CountWord(String, String) ,为什么会出现此错误以及如何在不使用 static 关键字的情况下使用它。 谢谢

public static void main(String[] args) {
    System.out.println(CountWord("the","test.txt"));
}

public int CountWord(String word, String textFilePath){

}

【问题讨论】:

标签: java static count


【解决方案1】:

尝试创建一个instance的类来调用这样的方法:

   public static void main(String[] args) {
        ClassName cn = new ClassName();
        System.out.println(cn.CountWord("the","test.txt"));
    }

    public int CountWord(String word, String textFilePath){

    }

【讨论】:

  • 没有理由回答完全重复的问题
  • 除非他们同时点击发送
  • 我之前写过,很有用
【解决方案2】:

bcoz CountWord() 是一个替代方法,要在 main()(一个 静态 方法)中访问它,您需要一个 CountWord() 类的实例

例如:

class Test{

     public static void main(String[] args) {
            Test t = new Test();
            System.out.println(t.CountWord("the","test.txt"));
        }
     public int CountWord(String word, String textFilePath){
        }
}

【讨论】:

    【解决方案3】:

    static 表示该方法属于一个对象。要使用此方法,您必须首先创建一个声明该方法的类的对象。

    假设你的班级看起来像这样:

    public class WordCounter{
        public int countWord(String word, String textFilePath){
             ....
        }
    }
    

    那么你的 main 方法应该是这样的:

        public static void main(String[] args){
             WordCounter counter = new WordCounter();
             counter.countWord("I am a String", "I am too");
        }
    

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2012-12-07
      相关资源
      最近更新 更多