import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
// Sammy Student: Data Analysis with Java File Processing
class DataAnalytics
{
public static void main(String args[])
{
// declare an object to receive the data
Scanner scan = new Scanner(System.in);
// declare an array list to hold the data
ArrayList list;
list = new ArrayList();
int count = 0;
int num = 0;
int val = 0;
String line = "";
try
{
// create or append to the file
FileWriter fileOut = new FileWriter("outData.txt");
BufferedWriter fout = new BufferedWriter(fileOut);
System.out.println("how many data items?");
count = scan.nextInt();
for (int i = 1; i <= count; i++)
{
System.out.println("enter a data value");
val = scan.nextInt();
fout.write(val + "\n");
}
System.out.println("thank you ... the data has been recorded!");
// close the output stream objects
fout.close();
fileOut.close();
scan.close();
// read the data
FileReader fileIn = new FileReader("outData.txt");
BufferedReader fin = new BufferedReader(fileIn);
while ((line = fin.readLine()) != null)
{
num = Integer.parseInt(line);
list.add(num);
System.out.println(num);
}
System.out.println("thank you ... the data has been received!");
fin.close();
fileIn.close();
System.out.println("display unsorted data");
DisplayData(list);
System.out.println("display sorted data");
BubbleSort(list);
//change the method with bubbleSort
}
catch(Exception e)
{
// catch an exception if any arises
System.err.println("Error: " + e.getMessage());
}
}
public static void DisplayData(ArrayList num)
{
for (int i = 0; i < num.size(); i++)
System.out.println(num.get(i).toString());
}
public static void BubbleSort(ArrayList num)
{
int j = 0;
boolean flag = true; // set the flag to true to begin first pass
int temp = 0; // define the holding variable
while (flag)
{
flag = false; //set flag to false awaiting a possible swap
for (j = 0; j < num.size() - 1; j++)
{
if (num.get(j) > num.get(j + 1))
// for descending sort change to <
{
temp = num.get(j); //swap the elements
num.set(j, num.get(j + 1));
num.set(j + 1, temp);
flag = true; //shows a swap occurred
}
}
}
System.out.println("display sorted data");
DisplayData(num);
}
}
Modify the Program
After testing your program that it displays the original data in an unsorted order and a sorted order, modify again the program to include each of these variations:
• Add a new method named MaxMin() that will find the smallest and largest value in the ArrayList after the data has been sorted.
• Add a new method named Average() that will find the average value in the ArrayList after the data has been sorted.
Save your program and perform a trial run of it. Test your program with data similar to that shown below.
[ Program Output ]
how many data items?
5
enter a data value
20
enter a data value
50
enter a data value
10
enter a data value
60
enter a data value
40
thank you . . . the data has been recorded!