方法将3个不同数组的所有值转换为它们的绝对值并返回所有值.3只转换第一个数组,而不转换下两个数组



我为一个类赋值,这个类基本上给了我三个不同的数组,主方法调用我的方法,调用makeThemAllPostive,它接受一个数组,并以其绝对值的形式打印出所有值。然而,我的方法只返回第一个被调用的数组,而忽略接下来调用我方法的两个数组。

我不知道还能尝试什么,我试过调整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]);
}

}

这是我的输出:

makeThemAllPostive测试:通过!应为[4,1,3,0,8,4,2],但您返回了[4,-1,-3,0,8,4,2]应为[8,42,1,42,1,2,42,5,0,2,42],但您返回了[-8,42,1,42,1,2,42,,5,2,42]

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

代码中明显的错误是,您执行了Math.abs,但没有将该值分配到任何位置,因此唯一的效果只是加热宇宙。试试这样的东西:

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

最新更新