在 main 方法中编写一个函数 - Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20888208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:02:20  来源:igfitidea点击:

Writing a function inside the main method - Java

javafunctionmethodsmain

提问by user3126119

Can you write a method inside the main method? For example I found this code:

你能在main方法里面写一个方法吗?例如我找到了这个代码:

public class TestMax {
    public static void main(String[] args) {
    int i = 5;
    int j = 2;
    int k = max(i, j);
    System.out.println("The maximum between is " + k);
}

 public static int max(int num1, int num2) {
    int result;
    if (num1 > num2)
       result = num1;
    else
       result = num2;

    return result; 
  }
}

Can the method max be coded inside the main method?

方法 max 可以在 main 方法中编码吗?

采纳答案by Spina

When Java 8 comes out, the Closure/Lambda functionality should make it so that you can define the max method in the main method. Until then, you'll only be able to define a method in the main method in special circumstances.

当 Java 8 出现时,Closure/Lambda 功能应该可以实现,以便您可以在 main 方法中定义 max 方法。在此之前,您只能在特殊情况下在 main 方法中定义方法。

As it happens, your question does fall into the special circumstance. There is an interface (Comparable) which encapsulates the logic of comparing two things of the same type. As a result, the code could be rewritten as follows:

碰巧,您的问题确实属于特殊情况。有一个接口(Comparable),它封装了比较相同类型的两个事物的逻辑。因此,代码可以改写如下:

public class TestMax {
  public static void main(String[] args) {
    int i = 5;
    int j = 2;
    Comparator<Integer> compare = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            // Because Integer already implements the method Comparable,
            // This could be changed to "return o1.compareTo(o2);"
            return o1 - o2;
        }
    };
    // Note that this will autobox your ints to Integers.
    int k = compare.compare(i, j) > 0 ? i : j;
    System.out.println("The maximum between is " + k);
  }
}

This only works because the comparator interface already exists in the standard Java distribution. The code could be made better through the use of libraries. If I were writing this code, I would add Google Guava to my classpath. Then I could write the following:

这只是因为比较器接口已经存在于标准 Java 发行版中。可以通过使用库来改进代码。如果我正在编写此代码,我会将 Google Guava 添加到我的类路径中。然后我可以写以下内容:

public class TestMax {
  public static void main(String[] args) {
    int i = 5;
    int j = 2;
    // The 'natural' ordering means use the compareTo method that is defined on Integer.
    int k = Ordering.<Integer>natural().max(i, j);
    System.out.println("The maximum between is " + k);
  }
}

I suspect that your question was more about the abilities of the Java language rather than standard practices having to do with ordering numbers (and other things). So this might not be useful, but I thought I'd share just in case.

我怀疑您的问题更多地是关于 Java 语言的能力,而不是与订购数字(和其他事情)有关的标准实践。所以这可能没有用,但我想我会分享以防万一。

回答by Keppil

No, you can't declare a method inside another method.

不,您不能在另一个方法中声明一个方法。

If you look closely at the code you provided it is just a case of bad formatting, the mainmethod ends before the maxmethod is declared.

如果您仔细查看您提供的代码,它只是格式错误的一种情况,main方法在max声明方法之前结束。

回答by Jim Garrison

If you want to use it, in this scenario, make it staticand place it in the class but outside the main method (as you have it in your code). Then you can call it from within main().

如果你想使用它,在这种情况下,制作它static并将它放在类中但在 main 方法之外(就像你在代码中那样)。然后你可以从内部调用它main()

回答by Sajad Karuthedath

you cannot directly define methodsinside other methods in Java ( main method too).

cannot directly define methods在 Java 中的其他方法中(也是 main 方法)。

You should write the method in the same class as main. 

Note:You could declare a class with methods inside another method

注意:您可以在另一个方法中声明一个包含方法的类

回答by Mad Physicist

With proper formatting, you will notice that the maxmethod appears in the same class as the mainmethod, but it is not IN the mainmethod.

使用正确的格式,您会注意到该max方法与该方法出现在同一类中main,但它不在该main方法中。

回答by Dharmendrasinh Chudasama

Yes, this is possible by lembdaexpression: for that you should use at least java 8

是的,这可以通过lembda表达式实现:为此,您应该至少使用java 8

import java.util.function.BiFunction;

public class TestMax {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> max = (a,b)-> a>b ? a : b;

        //now you can call method

        int i = 5;
        int j = 2;
        int k = max.apply(i, j);
        System.out.println("The maximum between is " + k);
    }
}

BiFunction is an functional interface java compiler internally converts lambda expression code as an anonymouse classwhich implements BiFunction interface and overrides apply() method which contains your code

Internal(compiler considered) code is:

BiFunction 是一个函数式接口 java 编译器在内部将 lambda 表达式代码转换为匿名类该类实现 BiFunction 接口并覆盖包含您的代码的 apply() 方法

内部(考虑编译器)代码是:

BiFunction<Integer, Integer, Integer> max = new BiFunction<Integer, Integer, Integer>(){
    public Integer apply(Integer a, Integer b){
        return a>b ? a : b; //your code
    }
}

回答by Kapil Tapsi

No. One cannot directly define method in methods in java. Except special conditions, like pre declared methods in inbuilt classes. The preferable method is define method in same class and ofcourse call it.

不能。在java中不能直接在方法中定义方法。除了特殊情况,比如内置类中预先声明的方法。最好的方法是在同一个类中定义方法,当然调用它。