【问题标题】:Need to make this return statement work, how?需要使这个返回语句工作,如何?
【发布时间】:2014-11-07 10:48:05
【问题描述】:

我在理解 return 语句方面有困难。

public class apples {

    public static void main(String[] args) {

        public static double slope(int x1, int y1, int x2, int y2) {

            double dy = y2 -y1;
            double dx = x2 - x1;
            return dy / dx;
        }

        slope(5, 11, 1, 3);
    }
}

我想返回dy / dx的总和。

【问题讨论】:

  • Java 的方法中不能有方法。
  • 那么我应该在我的 main 方法中放什么?
  • 注意 Java 命名约定 - 类名总是以大写字母开头。你是一个初学者,但至少从一开始就掌握它是件好事 :)

标签: java parameters return


【解决方案1】:

把你的方法放在主方法之外:

public static double slope(int x1, int y1, int x2, int y2) {

    double dy = y2 - y1;
    double dx = x2 - x1;
    return dy / dx;
}

public static void main(String[] args) {

    System.out.println("slope is : " + slope(5, 11, 1, 3));
}

【讨论】:

    【解决方案2】:

    在java等编程语言中,不能在其他方法中定义方法。在上面的代码中,您在 main(args) 方法中定义方法 slope(x1,y1,x2,y2)。只需将slope() 方法移到main() 之外。之后从任何其他方法调用该方法,现在从 main() 方法调用 slope(1,2,3,4)。这里 slope(x1,x2,y1,y2) 是静态方法,因此从静态方法调用时无需创建类苹果的对象来引用 slope() 方法。

    slope(x1,y1,x2,y2) 方法是完美的。 return 声明没有问题。

    记得在 apples 类的大括号中包含 slope() 方法。您的代码可以更改为以下

    公开课苹果{

    public static void main(String[] args) {        
    
       double d = slope(5, 11, 1, 3);
       System.out.println("return value : " + d);
    }
    public static double slope(int x1, int y1, int x2, int y2) {
    
            double dy = y2 -y1;
            double dx = x2 - x1;
            return dy / dx;
    }
    

    }

    【讨论】:

      【解决方案3】:

      返回总是退出该方法。返回值的类型必须与方法的类型相同。而且你不能在一个方法中有一个方法。这里你有方法 main 中的方法斜率。

      【讨论】:

        【解决方案4】:

        将你的斜率方法放在 main 方法之外,但放在你的 apples 类中。然后在main方法里面调用slope方法。

        【讨论】:

          【解决方案5】:

          你必须在主函数中编写函数的声明(如果有的话,带有参数) 喜欢slop(int, int,int );

          在 main 方法之后和类内部你必须定义你的 slop 方法

          希望它会有所帮助 谢谢

          【讨论】:

            猜你喜欢
            • 2013-03-20
            • 2016-02-13
            • 2013-11-29
            • 2021-12-01
            • 2021-04-28
            • 1970-01-01
            • 1970-01-01
            • 2014-01-30
            • 1970-01-01
            相关资源
            最近更新 更多