Hi I really need help with this Java program The assignment
Hi! I really need help with this Java program. The assignment is to:
Create a Java class called ArrayWorks. The constructor will ask the user how many numbers they are entering, then retrieving those numbers from the user. The numbers will be placed into an ArrayList created by the constructor. The ArrayList is the lone attribute of the ArrayWorks class. Write following methods:
size : This method returns the size of the ArrayList attribute
Ave : This method calculates and returns the average of the numbers on the array. Note that the average will not ALWAYS be a whole number, so use an appropriate return type.
Max : Returns the highest value on the array
Min : Returns the lowest value on the array
Any help would be greatly appreciated!:)
Solution
ArrayWorks.java
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayWorks {
Scanner scan =null;
ArrayList<Integer> list;
public ArrayWorks(){
scan = new Scanner(System.in);
System.out.print(\"Enter how many number of value: \");
int n = scan.nextInt();
list = new ArrayList<Integer>();
for(int i=0; i<n; i++){
System.out.print(\"Enter the number: \");
list.add(scan.nextInt());
}
}
public int size(){
return list.size();
}
public double Ave(){
int sum = 0;
for(int i=0; i<size(); i++){
sum = sum + list.get(i);
}
return sum/(double)size();
}
public int Max(){
int max = list.get(0);
for(int i=0; i<size(); i++){
if(max < list.get(i)){
max = list.get(i);
}
}
return max;
}
public int Min(){
int min = list.get(0);
for(int i=0; i<size(); i++){
if(min > list.get(i)){
min = list.get(i);
}
}
return min;
}
public static void main(String[] args) {
ArrayWorks obj = new ArrayWorks();
System.out.println(\"Size is \"+obj.size());
System.out.println(\"Average is \"+obj.Ave());
System.out.println(\"Max value is \"+obj.Max());
System.out.println(\"Min value is \"+obj.Min());
}
}
Output:
Enter how many number of value: 10
Enter the number: 4
Enter the number: 3
Enter the number: 2
Enter the number: 6
Enter the number: 8
Enter the number: 9
Enter the number: 7
Enter the number: 1
Enter the number: 5
Enter the number: 11
Size is 10
Average is 5.6
Max value is 11
Min value is 1

