简体   繁体   中英

Negative numbers in Array into positives Java

I know similar questions have been asked and answered, but my code still isn't working and I wanted to ask you for help.

In my Java code, I want to create a method which turns all negative integers of an array into positive ones.

In the main method, I then want to create an array, fill it with integers and call the method created above on it.

The compilers don't have a problem with my code, but the output is still filled with negative numbers. What do I do wrong?

Below my code (words in German , sorry for those who don't understand):

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]);
        }
    }
}

The output is:

1
-2
-42

Thanks in Advance!

Math.abs receives a number and returns its absolute value - a return value that you're currently ignoring. You need to assign it back to the array:

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;
}

I would do it with a void-method and output the array directly in this method after every element of the array makes an absolute value with Math.abs . Because otherwise you change the array in a method and return it, and you should avoid that. I hope I could help you like this

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM