使用具有循环的方法打印数组

时间:2014-03-24 19:09:21

标签: java arrays for-loop methods

我需要在方法内使用循环打印数组。我的代码有效,但只适用于一个数字。我需要打印数组,x增加1,y增加5 代码看起来应该是这样的

feet  meters |  meters    feet 
1.0  0.305   |  20.0    65.574
2.0  0.610   |  25.0    81.967
...    
9.0  2.745   |  60.0    196.721
10.0  3.050  |  65.0    213.115

这是我的代码

    double x = 1.0;
    double y = 20.0;

    double k = footToMeter(x);//gets footToMeter
    double m = meterToFoot(y);
    System.out.print("Feet\tMeters\t|   Meters\tFeet");
    System.out.printf("\n%.1f\t%.3f\t|   %.1f\t%.3f",x,k,y,m);
}//close main

public static double footToMeter(double foot) {
    double meter = 0.0;
    for (int i=0; i<10; i++) {
        meter = 0.305 * foot;
    }
    foot++;
    return meter;  
}//close footToMeter

public static double meterToFoot(double meter) {
    double foot = 0.0;
    for (int i=0; i<65; i++) {
        foot = 3.279 * meter;
    }
    meter++; 
    return foot;
}//close meterToFoot

1 个答案:

答案 0 :(得分:0)

正如我在你的回答评论中所提到的,请检查循环是否位于正确的位置。

从问题描述和代码中我会尝试这样的解决方案:

...
double x = 1.0;
double y = 20.0;
double k;
double m;

System.out.print("Feet\tMeters\t|   Meters\tFeet"); 
for (int i=0; i<10; i++) {
  k = footToMeter(x);
  m = meterToFoot(y);

  System.out.printf("\n%.1f\t%.3f\t|   %.1f\t%.3f",x,k,y,m);
  x = x+1;
  y = y+5;
 }
}

public static double footToMeter(double foot) {
 return 0.305 * foot;
}

public static double meterToFoot(double meter) {
 return 3.279 * meter;
}