Question
. In the method main, prompt the user for a non-negative integer and store it in an int variable num (Data validation is not required
. In the method main, prompt the user for a non-negative integer and store it in an int variable num (Data validation is not required for the lab). Create an int array whose size equals num+10. Initialize the array with random integers between 0 and 50 (including 0 and excluding 50). Hint: See Topic 4 Decision Structures and File IO slides page 42 for how to generate a random integer between 0 (inclusive) and bound (exclusive) by using bound in the nextInt method. 2. Define the following methods:
1) printArray accepts a one-dimensional array as its argument and print out the contents of the array.
2) getTotal accepts a one-dimensional array as its argument and returns the total of the values in the array. Try to use an enhanced for loop in the method.
3) getAverage accepts a one-dimensional array as its argument and returns the average of the values in the array as a floating-point value. Hints: Call getTotal method to avoid repetition of code.
4) getHighest accepts a one-dimensional array as its argument and returns the highest value in the array.
5) getLowest accepts a one-dimensional array as its argument and returns the lowest value in the array.
3. Call the printArray method to output the contents of the array.
4. Set the last element of the array to be the value of the eighth element minus twice the fifth element. Output the contents of the array again.
5. Display the total, the average, the highest, and the lowest value of the array by calling the above methods.
Starter code
port java.util.Random; import java.util.Scanner;
public class Lab5 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); System.out.print("Enter a non negative integer: "); int num = keyboard.nextInt(); int[] alpha = new int[num + 10]; Random rand = new Random(); for (int i = 0; i < alpha.length; i++) { alpha[i] = rand.nextInt(50);
} printArray(alpha); System.out.println("The total is: "); }
public static void printArray(int[] array) { //regular for loop for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); System.out.println("");
//Enhanced For Loop for (int n : array) { System.out.println(n + " "); } System.out.println("");
}
public static int getTotal(int[] array) { int total = 0; for (int i = 0; i < array.length; i++) { total += array[i]; } return total; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started