I have written a program that prints the contents of an array that are above a certain number (called average). It does this perfectly, but ti prints the empty elements as well (i.e. values of 0.0). How can I stop Java from printing the empty elements?
Thanks.
CODE:
import java.util.Scanner; import java.util.Arrays; // Create PriceArray Class public class PriceArray { // Create main Method public static void main(String[] args) { // Create array to hold 5 prices, declare variables double[] priceList = new double[5]; Scanner sc = new Scanner(System.in); // Get prices from the user and put them into the priceList array System.out.println("Please enter a price: "); int price; for (price=0; price < priceList.length; ++price) { System.out.print("Price "+(price+1)+": "); priceList[price] = sc.nextDouble(); if (priceList[price]<0) break; } System.out.println("Thank you!"); System.out.println("Total: " + sumArray(priceList)); System.out.println("Average: " + averageArray(priceList)); System.out.println("High Prices: " + formatList(highPrices(priceList, averageArray(priceList)))); } // Create sumArray Method public static double sumArray(double[] priceList) { // Declare variables double sum = 0; //Calculate the um of the elements in the PriceList Array for (int i = 0; i < priceList.length; i++) { sum += priceList[i]; } return sum; } // Create averageArray Method public static double averageArray(double[] priceList) { // Declare variables double average = 0; //Calculate the um of the elements in the PriceList Array for (int i = 0; i < priceList.length; i++) { average += priceList[i] / priceList.length; } return average; } // Create highPrices Method public static double[] highPrices(double[] priceList, double average) { average = averageArray(priceList); double[] highValues = new double[5]; int j=0; for (int i=0; i < priceList.length; ++i) if (priceList[i] > average) highValues[j++]=priceList[i]; return highValues; } // Create formatList Method public static String formatList(double[] priceList) { StringBuffer result = new StringBuffer(); for (int i=0; i < priceList.length; ++i) { if (i!=0) result.append(", "); result.append(priceList[i]); } return result.toString(); } }