40.8k views
4 votes
Complete the following method named replaceEvens that receives the parameter numbers which is an array of integers. The method must replace all elements of numbers that store even values with the negative of that value. That is, if the number 12 is found in a given position of numbers, then the method must replace the 12 with a -12. You can assume that initially all values in the array are integers greater than zero.

1 Answer

6 votes

Answer:

Following are the method definition to this question:

public class Neg //defining class Neg

{

public static void replaceEvens(int[] numbers) //defining a method replaceEvens that accepts array

{

int i; //defining integer variable

for(i = 0 ; i < numbers.length; i++) //defining foop to counts number

{

if(numbers[i]%2 == 0) //defining condition to check number is even

{

numbers[i] = numbers[i] * -1; //multiply the number by -1

}

}

for(i = 0 ; i < numbers.length; i++) // defining loop print array

{

System.out.print(numbers[i] + " "); //print array

}

}

public static void main(String[] as)//defining main method

{

int[] numbers = {12, 10, 18, 5, 2,22}; //defining array numbers and assign value

System.out.println("Elements of array: "); //print message

for(int i = 0 ; i < numbers.length ; i++) //defining loop to print message

{

System.out.print(numbers[i] + " "); //print array

}

System.out.println("\\ After replaceEvens"); //print message

replaceEvens(numbers); //calling method replaceEvens

}

}

Output:

please find the attachment.

Step-by-step explanation:

  • In the given program a static method replaceEvens is declared, in which array numbers pass as the parameter, inside the for method loop is declared, which counts array number in this loop if block is defined, that check-in array there is an even number.
  • In the condition is true it will multiply the number by -1, and output side the loop it will define another loop to print its value.
  • Inside the main method, a number array is declared, that first prints its value then call the method to print its change value.
Complete the following method named replaceEvens that receives the parameter numbers-example-1
User Blackandorangecat
by
3.1k points