0

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!

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Melosh
  • 9
  • 2

2 Answers2

0

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;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    A method that takes an array and returns an array probably should not return it's argument and modify it. Either return `void` or create a new array. – Johannes Kuhn Apr 11 '20 at 20:16
0

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);
        }
    }
}
SwissCodeMen
  • 4,222
  • 8
  • 24
  • 34