Java Long Max 方法

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

Long.max() 方法用于返回作为参数传递的两个长整型数中数值较大的值(最大值)。如果传递一个正数和一个负数,它将返回正数;如果传递的两个数都是负数,则返回绝对值较小的值。

创建一个 Java 文件

我们将创建一个 Java 文件来编写本示例的代码。在 Ubuntu 中打开终端,并通过运行以下命令导航到 project 目录:

cd ~/project/

现在,通过运行以下命令创建一个名为 LongMaxExample.java 的文件:

touch LongMaxExample.java

编写代码

LongMaxExample.java 文件中,编写以下代码:

public class LongMaxExample {
    public static void main(String[] args) {
        long a = 5485;
        long b = -3242;
        long c = -5645;

        long max1 = Long.max(a, b);
        long max2 = Long.max(b, c);

        System.out.println("The maximum of " + a + " and " + b + " is " + max1);
        System.out.println("The maximum of " + b + " and " + c + " is " + max2);
    }
}

保存并编译代码

编写完代码后,保存文件并关闭编辑器。

使用以下命令编译 Java 文件:

javac LongMaxExample.java

运行代码

成功编译后,你可以使用以下命令运行代码:

java LongMaxExample

这将输出以下结果:

The maximum of 5485 and -3242 is 5485
The maximum of -3242 and -5645 is -3242

用户输入演示

编写以下代码来演示如何将 Long.max() 与用户输入结合使用:

import java.util.Scanner;

public class LongMaxExample {
    public static void main(String[] args) {
        try {
            Scanner sc= new Scanner(System.in);

            System.out.println("Enter the first number:");
            long num1 = sc.nextLong();
            System.out.println("Enter the second number:");
            long num2 = sc.nextLong();

            System.out.println("The maximum of " + num1 + " and " + num2 + " is " + Long.max(num1, num2));
        }
        catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

保存并编译代码

编写完代码后,保存文件并关闭编辑器。

使用以下命令编译 Java 文件:

javac LongMaxExample.java

运行代码

成功编译后,你可以使用以下命令运行代码:

java LongMaxExample

这将输出以下结果:

Enter the first number:
-5
Enter the second number:
8
The maximum of -5 and 8 is 8

输入两个 long 类型的值,程序将输出这两个数中的最大值。

总结

恭喜!你已经学习了 Java Long.max() 方法的概念和实现。该方法用于查找两个 long 类型数值中的最大值。我们还演示了如何在程序中结合用户输入使用该方法。