JAVA PROGRAM HELP:
Your program should have the following functionality:
Read the integers from the file into an ArrayList object that is initially created with the default ArrayList constructor.
Compute the average of the integers from the input file.
Compute the sum of the integers from the input file that have even values.
Print a formatted report with labeled output with the following:
Print the number of integers read from the file.
Print the average of the integers read from the file.
Print the sum of the integers read the file that have even values.
Print a list of the integers read from the file.
Search through the ArrayList for a values of 31 and replace all of them with the value 3100.
Add the integers -1, -2, -3, -4, -5 to the beginning of the ArrayList.
Add the integers 101, 102, 103, 104 to the end of the ArrayList.
Continue the formatted report with the following:
Print the list of the integers in the ArrayList after the modifications from items 5, 6, and 7 are made.
Expert Answer
Hi here’s the complete code, with comments to help you understand
/* package whatever; // don’t place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) { //read file until EOF
String sCurrentLine;
List<Integer> list = new ArrayList<Integer>();
while ((sCurrentLine = br.readLine()) != null) {
list.add(Integer.parseInt(sCurrentLine)); //add to arraylist
}
int total=0;
int eventotal=0;
int evencount=0;
double average=0.0;
double evenaverage=0.0;
for(int i = 0; i<list.size(); i++) //get totals
{
total = total+list.get(i);
if(list.get(i)%2==0)
{
evencount++;
eventotal+=list.get(i);
}
}
int n=list.size();
average=total/list.size();
evenaverage=eventotal/evencount; //even averages
System.out.println(“The numbers of integers in file are:”+list.size());
System.out.println(“The average of integers in file are:”+average);
System.out.println(“The sum of even numbers in file are:”+eventotal);
System.out.println(“The numbers in file are:”+list);
Collections.replaceAll(list, 31,3100); //replaces 31 with 3100
list.add(0, -1); //adding to index 0 i.e start
list.add(1, -2);
list.add(2, -3);
list.add(3, -4);
list.add(4, -5);
list.add(n+1, 101); //adding to index n+1 that is end
list.add(n+2, 102);
list.add(n+3, 103);
list.add(n+4, 104);
System.out.println(“The numbers in file are:”+list);
} catch (IOException e) {
e.printStackTrace();
}
}
}