【问题标题】:Negative numbers in Array into positives Java将数组中的负数转换为正数 Java
【发布时间】:2020-04-11 20:04:51
【问题描述】:

我知道有人提出并回答了类似的问题,但我的代码仍然无法正常工作,我想向您寻求帮助。

在我的 Java 代码中,我想创建一个将数组的所有负整数转换为正整数的方法。

main方法中,然后我想创建一个数组,用整数填充它并调用上面创建的方法。

编译器对我的代码没有问题,但输出仍然充满负数。我做错了什么?

下面是我的代码(German里的字,不明白的见谅):

public class BetragAnwendung {
    public int[] bildeBetrag(int[] werte) {
        for (int i : werte) {
            Math.abs(i);
        }
        return werte;
    }

    public static void main(String[] args) {
        BetragAnwendung betragAnwendung = new BetragAnwendung();
        int[] array = { 1, -2, -42 };
        int[] positiveArray = betragAnwendung.bildeBetrag(array);
        for (int i = 0; i < array.length; i++) {
            System.out.println(positiveArray[i]);
        }
    }
}

输出是:

1
-2
-42

提前致谢!

【问题讨论】:

  • 仔细想想这个说法:Math.abs(i);

标签: java arrays math integer


【解决方案1】:

Math.abs 接收一个数字并返回它的绝对值 - 您当前忽略的返回值。您需要将其分配回数组:

public int[] bildeBetrag(int[] werte) {
    for (int i = 0; i < werte.length; ++i) { // Note we're iterating the array's indexes!
        werte[i] = Math.abs(werte[i]);
    }

    return werte;
}

【讨论】:

  • 一个接受一个数组并返回一个数组的方法可能不应该返回它的参数并修改它。要么返回void,要么创建一个新数组。
【解决方案2】:

我会使用 void-method 来完成,并在数组的每个元素都使用Math.abs 生成绝对值后直接在此方法中输出数组。因为否则你在一个方法中改变数组并返回它,你应该避免这种情况。希望能帮到你

public class negativeInPositiveElementsArray {
    public static class BetragAnwendung {

        public static void bildeBetrag(int[] werte) {
            for (int i = 0; i < werte.length; ++i) { // Note we're iterating the array's indexes!
                werte[i] = Math.abs(werte[i]);
                System.out.println(werte[i]);
            }
        }


        public static void main(String[] args) {

            BetragAnwendung betragAnwendung = new BetragAnwendung();

            int[] array = {1, -2, -42};

            betragAnwendung.bildeBetrag(array);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多