How to show certain numbers from an Array in Java?

  • A+
Category:Languages

I want to single out only positive numbers in one line and only negative numbers in one line, but they only show one by one with the text. Here's my code:

int[] array = {2, -5, 4, 12, 54, -2, -50, 150};     Arrays.sort(array);     for (int i = 0; i < array.length; i++) {         if (array[i] < 0) {             System.out.println("Less than 0: " + array[i]);          } else if (array[i] > 0) {             System.out.println("Greater than 0: " + array[i]);         }      } 


Since you sorted the values, you know all negative values come before the positive values, so you start printing values and then switch to new line when you encounter the first positive value.

E.g. like below, which can also handle an array of all negative values, an array of all positive values, and even an empty array.

This only uses Java constructs you've already shown you know.

int[] array = {2, -5, 4, 12, 54, -2, -50, 150}; Arrays.sort(array); for (int i = 0, iFirstPositive = 0; i < array.length; i++) {     if (array[i] < 0)         iFirstPositive = i + 1; // Assume index of first positive value is next     if (i == iFirstPositive) {         if (i != 0)             System.out.println(); // End line of negative values         System.out.print("Greater than 0: "); // Start line of positive values     } else if (i == 0) {         System.out.print("Less than 0: "); // Start line of negative values     } else {         System.out.print(", ");     }     System.out.print(array[i]); } if (array.length != 0) {     System.out.println(); // End line if anything printed } 

Output

Less than 0: -50, -5, -2 Greater than 0: 2, 4, 12, 54, 150 

 

Simpler, but slightly less optimal, you can also just do it with two loops:

int[] array = {2, -5, 4, 12, 54, -2, -50, 150}; Arrays.sort(array); System.out.print("Less than 0:"); for (int i = 0; i < array.length; i++) {     if (array[i] < 0) {         System.out.print(" " + array[i]);     } } System.out.println(); System.out.print("Greater than 0:"); for (int i = 0; i < array.length; i++) {     if (array[i] > 0) {         System.out.print(" " + array[i]);     } } System.out.println(); 

Output

Less than 0: -50 -5 -2 Greater than 0: 2 4 12 54 150 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: