Free Response Practice Question (with solution)- Sales Array
<-- Back to Large Integer Array | Next to Distance Array--> |
Sales Array
Write a Java program that stores the daily average sales at a particular store for a grocery store for 12 consecutive days. You need to use an array to store this data. Next, calculate the length of the longest high-sale sequence days for the given store. High-sale sequence days are defined as a sequence of three or more consecutive days with a daily average sale which is higher than a given average sale (avgSaleThreshold). The program should print only the length of the high-sale sequence days (>=3) or else print an appropriate message.
For e.g., consider following as the values in the sales array:
200, 198, 202, 203, 187, 205, 190, 194, 209, 202, 207, 193
For avgSaleThreshold = 200
The following will be the high-sale sequence days:
Those marked in orange will not be considered, since the number of days is less than 3.
While, those marked in green will be considered, since the number of days is greater than or equal to 3.
The program will output 3.
Solution:
import java.util.InputMismatchException; import java.util.Scanner; public class SalesArray { public static void main(String[] args) { int SIZE =12; int [] salesArr = new int [SIZE]; try (Scanner input = new Scanner(System.in)) { int number; System.out.print("Enter the sales information for 12 consecutive days: "); for (int k=0; k < salesArr.length; k++) { number = input.nextInt(); salesArr[k]= number; } int avgThreshold=0; System.out.println("Enter the average threshold sale: "); avgThreshold = input.nextInt(); int length=0; int maxLength=0; int index=0; boolean exit=false; for (int i=0; i< salesArr.length; i++) { length=0; index=0; if (salesArr[i] > avgThreshold) { index =i+1; length++; exit=false; for (; index < salesArr.length && !exit; index++) { if (salesArr[index]> avgThreshold) length++; else { // exit from this loop exit = true; } } } if (maxLength < length) maxLength=length; } if (maxLength >= 3) System.out.println("The max length of the high-sale sequence days: "+ maxLength); else System.out.println("There are no high-sale sequence days greater than or equal to 3"); } catch (InputMismatchException e) { System.out.println("Error reading input"); } } }
Java project file:
<-- Back to Large Integer Array | Next to Distance Array--> |