交换和反转两种方法

时间:2015-04-27 18:46:38

标签: java methods reverse swap

使用两种方法创建一个名为Flip的类:

public float[] swap(float[] pair)

swap方法应该包含一个包含两个浮点数的数组。它应该返回一个在交换位置包含相同两个数字的数组。例如,如果我像这样调用你的方法交换:

float[] x = { 3.14, 2.71 }

float[] y = swap(x);

Ln.p(y[0] + “, “ + y[1]);

调用交换方法的方法应打印出2.71, 3.14

public double[] reverse(double[] reverse, int length)

反向方法应该包含一个包含任意数量的双精度数组(长度指定)。它应该以相反的顺序返回一个包含所有这些数字的数组。您不必使用for循环,但这是编写此方法的最简单方法。如果我按照这样的方式调用你的方法:

double[] a = { 0.33, 0.66, 0.25, 0.5, 0.75 }

double[] b = reverse(a, 5);

for (int i = 0; i < 5; i++) Ln.p(b[i] + “ “);

调用反向方法的方法应打印出0.75 0.5 0.25 0.66 0.33

---所以我有浮动的第一个,但我正在寻找第二部分的起点或方向。

import java.util.Scanner;

public class Flip 
enter code here{


public float[] swap(float[] pair) 
{
    float x = 0;
    float y = 0;

    int xi = Float.floatToIntBits(x);
    int yi = Float.floatToIntBits(y);
    xi = yi - xi;
    yi = yi - xi;
    xi = xi + yi;
    x = Float.intBitsToFloat(xi);
    y = Float.intBitsToFloat(yi);

    System.out.printf("My method calling your swap method is...." +x,y); 

    return null;
}

public double[] reverse(double[] reverse, int lenght)
{
    double[] a = { 0.33, 0.66, 0.25, 0.5, 0.75 };

    double[] b = reverse(a, 5);

    for (int i = 0; i < 5; i++) Ln.p(b[i] + “ “);

    return reverse;

}

}

1 个答案:

答案 0 :(得分:0)

要换成大小为2的数组中的elemtens,我会这样做:

float[] array = {2.7, 3.2};
float x = array[1];
array[1] = array[0];
array[0] = x;

也不要忘记实际返回交换的阵列!

要反转整个List或Array,我建议在Collection中使用reverse()方法。看一眼 http://www.tutorialspoint.com/java/util/collections_reverse.htm

如果您想使用自己的方法执行此操作,请尝试使用相同大小的输出数组中的输入数组复制值,但反过来:

float[] input = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
float[] out = new float[input.length];
for(int i=0;i<input.length; i++) {
  out[i]=input[input.length-i-1];
}
相关问题