0

我对在哪里使用以下方法感到困惑:

initialize(alpha);
print(alpha);

我做了下面的程序,我得到了我想要的信息,但我不知道如何使用这些方法来更改代码但得到相同的输出。也许是我看得太多了?任何帮助将不胜感激。

import java.util.*;

public class ProgEx_Ch9_No1{

static Scanner console = new Scanner(System.in);    

public static void main(String[] args){

    double[] alpha = new double[50];

    for(int i=0; i<alpha.length; i++){

        alpha[i] = Math.pow(1,2);
        System.out.println("Alpha[" + i + "]: " + alpha[i]);

        if(i < 25){
            alpha[i] = Math.pow(1,2);
            System.out.println("Alpha[" + i + "]: " + alpha[i]);
        }
        else{
            alpha[i] = i*3;
            System.out.println("Alpha[" + i + "]: " + alpha[i]);
        }
    }

    for(int i=0; i<alpha.length; i++){
        System.out.print(alpha[i] + " ");
        if ((i + 1)%10 == 0)
            System.out.println();

}

}
}
4

2 回答 2

1

这听起来像是一个关于重构的问题,所以你可能有这样的方法:

public static double[] initialize(double[] alpha)
{
    for(int i=0; i<alpha.length; i++)
    {
        alpha[i] = Math.pow(1,2);
        System.out.println("Alpha[" + i + "]: " + alpha[i]);

        if(i < 25)
        {
            alpha[i] = Math.pow(1,2);
            System.out.println("Alpha[" + i + "]: " + alpha[i]);
        }
        else
        {
            alpha[i] = i*3;
            System.out.println("Alpha[" + i + "]: " + alpha[i]);
        }
    }

    return alpha;
}

然后,您可以从 main 调用此方法:

public static void main(String[] args)
{
    double[] alpha = new double[50];
    alpha = initialize(alpha);
    ....
}
于 2013-04-17T02:31:03.937 回答
1

我认为您正在寻找类似的东西:

public static void main(String[] args)
{
    double[] alpha = initialize();

    print(alpha);        

}

private static double[] initialize() {

    double[] alpha = new double[50];

    for(int i=0; i<alpha.length; i++)
    {
        alpha[i] = Math.pow(1,2);
        System.out.println("Alpha[" + i + "]: " + alpha[i]);

        if(i < 25)
        {
            alpha[i] = Math.pow(1,2);
            System.out.println("Alpha[" + i + "]: " + alpha[i]);
        }
        else
        {
            alpha[i] = i*3;
            System.out.println("Alpha[" + i + "]: " + alpha[i]);
        }
    }
    return alpha;
}

public static void print(double[] alpha) {
    for(int i=0; i<alpha.length; i++)
    {
        System.out.print(alpha[i] + " ");
        if ((i+ 1)%10 == 0)
            System.out.println();
    }
}
于 2013-04-17T02:32:34.910 回答