Question: JAVA QUESTION (Please dont use complicated code, weve only had 3 classes on conditional statements , loops and expressions plus arrays) Create code that asks

JAVA QUESTION (Please dont use complicated code, weve only had 3 classes on conditional statements , loops and expressions plus arrays)

Create code that asks a user to enter 5 integers and store them in the array.

This code should only be written once

Hint: Use a for loop utilising the array.length construct to avoid code repetition.

for(int i = 0; i < array.length; i++)

Once the user has assigned all 5 values to the array, the program should print the array contents to the terminal window using the Java Arrays utility class as described in slide 4. Write a helper method that takes 2 parameters, a String which describes the array, and an array, both of which should be printed to the terminal window.

public static void printArray(String msg, int[] array)

System.out.println(msg + " " + Arrays.toString(array));

Returning to the main method, you will need to write calls for the methods in the following two exercises.

Use the array as an argument for the following methods,

all of which should return results

: sum

repeat

You should print the returned result from each method before calling the next, using the printArray method if appropriate.

Implement the method:

public static int sum(int[] array

that returns the sum of all elements in an array:

For example, if you call it with [1, 4, 9, 16, 9]

then it returns

39 (1 + 4 + 9 + 16 + 9)

Before writing the code, consider the following: Will the method require new variable/s? How can this be accomplished for arrays of any length?

Implement the method:

public static int[] repeat(int[] array) t

hat returns an array containing the original array elements repeated 3 times.

For example, if you call it with [1, 4, 9], then the method should return a new array containing [1, 4, 9, 1, 4, 9, 1, 4, 9]. Hints: 1.

Create a new array of size determined by array.length 2.

Use a for loop(s) to copy values from one array to the other in the required order.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!