Task #12: Using Arrays and Methods
In this task, you are being asked to write methods that manipulate arrays in Java.
Write a method that swaps the value of the array in such a way that all negative values comes
before the positive values in the array. The method should then returns the array.
You may use the following header for this method:
static int[] negativeBeforePositive(int[] array)
NOTE: Declare and initialize the array without taking the input from user.
Treat the 0 as a value greater then negative numbers, but lesser than positive numbers.
You may declare some temporary arrays for your help.
1. Create a program called ArrayNegativeBeforePositiveLab1.java.
2. Create appropriate variables and assign values using a Scanner object.
3. Correctly display appropriate messages.
import java.util.Arrays;
public class ArrayNegativeBeforePositiveLab1 {
static int[] negativeBeforePositive(int[] array) {
int[] result = new int[array.length];
for (int i = 0, l = 0, r = array.length - 1; i < array.length; i++) {
if (array[i] < 0) {
result[l++] = array[i];
} else if (array[i] > 0) {
result[r--] = array[i];
}
}
return result;
}
public static void main(String[] args) {
int[] array = {5, 6, 0, 2, -3, 0, 5, 9, -8, -5, 2, 6, -4, 0};
System.out.println(Arrays.toString(negativeBeforePositive(array)));
}
}
Comments
Leave a comment