22.1k views
0 votes
Write Java code that creates an array of n integers myArray, by taking n integers from the user with duplications, and do the following:

1- Print the elements of myArray,
2- Calculate the sum and the mean of myArray elements,
3- Copy the values of myArray to an array list named myArrayList, the array list must contain the elements of myArray without duplication,
4- Calculate the sum and the mean of myArrayList elem

1 Answer

5 votes

Answer:

this should be what you need

Step-by-step explanation:

import java.util.*;

public class ABC{

public static void main(String[] args) {

int n;

//create scanner object

Scanner sc = new Scanner(System.in);

//ask for size of array

System.out.print("Enter the size of array (n): ");

//read the input

n = sc.nextInt();

//create an array of n length

int [] myArray = new int[n];

//ask user for array elements

System.out.printf("Enter %d integers: ", n);

//read array elements

for(int i =0 ;i <5; i++)

myArray[i] = sc.nextInt();

//print the elements if myArray

System.out.print("1 - The values of myArray are: [");

for(int i =0 ; i < n; i++){

System.out.print(myArray[i]);

if(i < n-1)

System.out.print(", ");

}

System.out.print("]\\");

//calculate mean and sum of myArray elements

int sum = 0;

double mean = 0;

for(int i = 0; i < n; i++)

sum += myArray[i];

mean = (sum*1.0)/n;

//print the sum and mean of myArray

System.out.printf("2 - The sum is: %d. The mean is: %.1f\\", sum, mean);

//create an arraylist

ArrayList<Integer> myArrayList = new ArrayList<Integer>();

//copy the value of myArray to an arraylist without duplicates

for(int i = 0; i < n; i++){

if(!myArrayList.contains(myArray[i]))

myArrayList.add(myArray[i]);

}

sum = 0; mean = 0;

//display the values of myArrayList

System.out.print("3 - The values of myArrayList are: [");

for(int i =0 ; i < myArrayList.size(); i++){

System.out.print(myArrayList.get(i));

if(i < myArrayList.size()-1)

System.out.print(", ");

}

System.out.print("]\\");

//calculate sum and mean of myArrayList elements

for(int i = 0; i < myArrayList.size(); i++)

sum += myArrayList.get(i);

mean = (sum*1.0)/myArrayList.size();

//print the sum and mean of myArrayList

System.out.printf("4 - The sum is: %d. The mean is: %.2f\\", sum, mean);

}

}

User Aravindh Kuppusamy
by
5.4k points