Chris Chris - 2 months ago 4
Java Question

JAVA: Replacing number in array, with the numbers position and print out

I have a small problem here. I want to replace all negative numbers in an array with the numbers position. My problem is that the array gets printed out, before the numbers are replaced, and I want to print out the array after it gets replaced...
Here is my code:

public class oppgave33{

public static void main(String[] args) {

int[] heltall = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int sumNeg = 0;

while(counter < heltall.length){

//array print out

System.out.println("array[" + counter + "] = " + heltall[counter]);


if(heltall[counter] < 0){
System.out.println(heltall[counter]);

}

//replacing negative numbers

if(heltall[counter] < 0 ){
heltall[counter]=counter;
}
if(heltall[counter] < 0){
sumNeg++;
}

//negative numbers position print out

if(heltall[counter] < 0 ){
System.out.println("Negative numbers position in array is : " + counter);
}

counter++;
}

//printing out how many negative numbers

System.out.println("There are : " + sumNeg + " negative numbers.");


}
}


Final note: if you remove the if setting, where the negative numbers are replaced by their position in array, you will get position to negative numbers printed out, and also how many negative numbers there are.
I hope you can help me! :) Thank you!

Answer

You have too many redundant conditions in your code. Your attempt is very close, you can simply do the following:

while (counter < heltall.length) {
    // if the number is negative, replace it with its index
    if (heltall[counter] < 0) {
        heltall[counter] = counter;
    }
    counter++;
}
// outside the loop
System.out.println(Arrays.toString(heltall));

Important tip: In such cases, you should debug your code. This will help you better understanding the flow of your code, and discover problems that you're not aware of them. I highly recommend you debugging your current code, and only then try to fix it.