Java方法实现

时间:2016-02-15 06:38:49

标签: java methods

我需要将方法实现到一个简单的程序中,以便用Java熟悉它们。

到目前为止我的代码是:

import java.util.*;

public class Lab5a
{
    public static void main(String args[])
    {
        double[] a = {1, 0, 0};
        double[] b = {0, 1, 1};
        double[] c = {1, 1, 1};
        double[] d = {0, 0, 1};

        double ab = Math.sqrt (
                (a[0]-b[0])*(a[0]-b[0]) +
                (a[1]-b[1])*(a[1]-b[1]) +
                (a[2]-b[2])*(a[2]-b[2]) );

        double ac = Math.sqrt (
                (a[0]-c[0])*(a[0]-c[0]) +
                (a[1]-c[1])*(a[1]-c[1]) +
                (a[2]-c[2])*(a[2]-c[2]) );

        double ad = Math.sqrt (
                (a[0]-d[0])*(a[0]-d[0]) +
                (a[1]-d[1])*(a[1]-d[1]) +
                (a[2]-d[2])*(a[2]-d[2]) );

        System.out.println("ab=" + ab + ",  ac=" + ac + ",  ad=" + ad);     
    }
}

我的指示是:<​​/ p>

Next, copy the class to Lab5b.java, and replace the individual distance calculations by calls to a single
public static method that computes the distance between two points passed in as parameters. Also, implement
the method. Your method should have a signature something like the following:

    public static double distance(double[] a, double[] b)

我对Java非常陌生,并且正在努力理解语句的确切含义。

1 个答案:

答案 0 :(得分:-1)

您的代码应该用于定义和调用具有不同参数的新方法。

import java.util.*;

public class Lab5b {
    public static void main(String args[]) {
        double[] a = { 1, 0, 0 };
        double[] b = { 0, 1, 1 };
        double[] c = { 1, 1, 1 };
        double[] d = { 0, 0, 1 };

        // Call the method
        System.out.println("ab=" + distance(a, b) + ",  ac=" + distance(a, c) + ",  ad=" + distance(a, d));
    }

    // Define method
    public static double distance(double[] a, double[] b) {
        double dist = 0;
        dist = Math.sqrt (
                (a[0]-b[0])*(a[0]-b[0]) +
                (a[1]-b[1])*(a[1]-b[1]) +
                (a[2]-b[2])*(a[2]-b[2]) );

        return dist;
    }
}