In: Computer Science
Write a java program that will ask the user to enter integers (use loops) until -100 is entered. The program will find and display the greatest, the smallest, the sum and the average of the entered numbers. also write a separate driver class which will be used to run and display the greatest, the smallest, the sum and the average of the entered numbers.
Thanks!!
import java.util.*;
class FindAndDisplay{
ArrayList<Integer> arr = new ArrayList<Integer>(); //ArrayList to store dynamic values
public void input(){ //To take inputs
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n!=-100){ /*check -100 is entered or not if not then add it to list and enter another the number*/
arr.add(n);
n=sc.nextInt();
}
}
public int sum(){ //Sum of the numbers
int s=0;
for(int i=0;i<arr.size();i++){
s+=arr.get(i);
}
return s;
}
public int smallest(){ //Smallest of numbers
int minvalue=0;
for(int i=0;i<arr.size();i++){
if(i==0){
minvalue=arr.get(i);
}
else{
if(arr.get(i)<minvalue){
minvalue=arr.get(i);
}
}
}
return minvalue;
}
public int greatest(){ //Greatest of numbers
int maxvalue=0;
for(int i=0;i<arr.size();i++){
if(i==0){
maxvalue=arr.get(i);
}
else{
if(arr.get(i)>maxvalue){
maxvalue=arr.get(i);
}
}
}
return maxvalue;
}
public double average(){ //average of numbers
int s=0;
for(int i=0;i<arr.size();i++){
s+=arr.get(i);
}
double d1,d2;
d1=s;
d2=arr.size();
return d1/d2;
}
}
public class driver{
public static void main(String[] args) {
FindAndDisplay f=new FindAndDisplay();
System.out.println("Enter integers ,enter -100 to stop ");
f.input();
System.out.println("Results::");
System.out.println("The Greatest of the numbers: "+f.greatest());
System.out.println("The Smallest of the numbers: "+f.smallest());
System.out.println("The Sum of the numbers: "+f.sum());
System.out.println("The Average of the numbers: "+f.average());
}
}
INPUT&OUTPUT:
Enter integers ,enter -100 to stop
100
400
120
230
254
650
-100
Results::
The Greatest of the numbers: 650
The Smallest of the numbers: 100
The Sum of the numbers: 1754
The Average of the numbers: 292.3333333333333
***Still have doubt ask in comment section***