在main方法内编写函数-Java

您可以在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;

}

}

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

回答:

当Java 8发布时,Closure /

Lambda功能应该可以实现,以便您可以在main方法中定义max方法。在此之前,您只能在特殊情况下在main方法中定义一个方法。

碰巧的是,您的问题确实属于特殊情况。有一个接口(可比较),其中包含比较两个相同类型的事物的逻辑。结果,该代码可以如下重写:

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);

}

}

这仅起作用,因为标准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);

}

}

我怀疑您的问题更多是关于Java语言的功能,而不是与订购数字(及其他事物)有关的标准实践。因此,这可能没有用,但我想以防万一。

以上是 在main方法内编写函数-Java 的全部内容, 来源链接: utcz.com/qa/414105.html

回到顶部