将 3 个不同数组的所有值都转换为它们的绝对值的方法,并且 return 所有 3 只保留第一个数组而不是接下来的两个数组

Method to turn all values of 3 different arrays into their absolute values and return all 3 keeps only turning the first array but not the next two

我有一个 class 的分配,它基本上给我三个不同的数组,主要方法调用我的方法调用 makeThemAllPostive,它接受一个数组并以绝对值形式打印出所有值。但是,我的方法仅 returns 调用的第一个数组,而忽略调用我的方法的接下来的两个数组。

我不知道还能尝试什么,我已经尝试调整我的 for 循环以便我可以尝试以不同的方式计算绝对值,或者添加更多 for 循环来尝试执行每个数组,并且没有任何效果。

这里是调用我的方法的主要方法部分

System.out.println("\nmakeThemAllPostive test:");
makeThemAllPostive(array1);
String actual = Arrays.toString(array1);
System.out.println(actual.equals("[2, 42, 1]") ? "Passed!"
  : "Expected [2, 42, 1] but you returned " + actual);
makeThemAllPostive(array2);
actual = Arrays.toString(array2);
System.out.println(actual.equals("[4, 1, 3, 0, 8, 4, 2]") ? "Passed!"
  : "Expected [4, 1, 3, 0, 8, 4, 2] but you returned " + actual);
makeThemAllPostive(array3);
actual = Arrays.toString(array3);
System.out.println(
  actual.equals("[8, 42, 1, 42, 1, 1, 2, 42, 5, 0, 2, 42]") ? "Passed!"
    : "Expected [8, 42, 1, 42, 1, 1, 2, 42, 5, 0, 2, 42] but you returned "
      + actual);

这是我的方法

public static void makeThemAllPostive(int[] arr)
  {

    int i = 0;
    for (i = 0; i < arr.length; i++)
    {
      Math.abs(arr[i]);
    }


  }

这是我的输出:

makeThemAll正面测试: 通过! 预期 [4, 1, 3, 0, 8, 4, 2] 但你返回 [4, -1, -3, 0, 8, -4, 2] 预期 [8, 42, 1, 42, 1, 1, 2, 42, 5, 0, 2, 42] 但你返回 [-8, 42, 1, 42, -1, 1, -2, 42, - 5, 0, 2, 42]

我的预期输出应该是所有 3 个测试都通过了,但只有第一个通过了 :(

您的代码中明显的错误是您做了 Math.abs 但您没有在任何地方分配该值,因此唯一的影响只是加热宇宙。尝试这样的事情:

for (int i = 0; i < arr.length; i++)
{
    arr[i] = Math.abs(arr[i]); // assign abs back!
}