繁体   English   中英

接受两个整数并返回两个整数中较大者的代码

[英]A code that will accept two integers and return the larger of the two integers

这是我有史以来的第一门编码课,对于这一切我还是很陌生。 我正在尝试创建一个将接受两个数字并返回两个数字中较大的一个的代码。 例如,如果给定函数da整数7和12,则该函数将返回da整数12。这是我到目前为止编写的代码,但远远不够正确。

 public class Return
    {
        public static void main(String[] args) 
        {
           public static int max("int num1, int num2,");
              int result;
              if (num1 > num2)
                result = num1;
              else
                result = num2;
            return result;

            }
        }

Java没有嵌套方法。 您在方法内部编写方法。 将您的方法移到外面,会有一些语法错误

public class Return
{
public static void main(String[] args) 
{
   int result = max (3,4);
   System.out.println(result);

}

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

        }
}

我建议您阅读一些编程的基本概念和所使用的语言。 但是,让我尝试帮助您。 您的代码应类似于:

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

    public static void main(String[] args) {
        System.out.println(max(1, 2));

    }

您的代码中的错误是:

  1. main内部声明的max方法。
  2. 参数在引号“ int num1,int num2”内传递,这是错误的。
  3. 没有max定义
  4. 不是要求maxmain

我希望它有助于理解代码问题。

此短代码将从两个整数返回较大的一个。

public static int larger(int a, int b)
{
    return a >= b ? a : b; 
}

复制此方法粘贴到所需的类并调用此方法

larger(12, 7);

根据您的班级:

public class Return
{
    public static int larger(int a, int b)
    {
        return a >= b ? a : b; 
    }

    public static void main(String[] args) 
    {      
        int larger127 = larger(12,7);
        System.out.println("The larger int from 12 and 7 is: " + larger127);
    }
}

您不能在另一个方法中包含一个方法。 像这样做:

public static void main(String[] args) {        
    int result = max (3,4);
    System.out.println(result);
}

private static int max(int i, int j) {
    return i > j ? i : j; 
}

max使用ternary operator查找两个数字中的最大值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM