我对使用以下方法的地方感到困惑:
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();
}
}
}
答案 0 :(得分: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;
}
然后,您可以从主要方法调用此方法:
public static void main(String[] args)
{
double[] alpha = new double[50];
alpha = initialize(alpha);
....
}
答案 1 :(得分: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();
}
}