Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Design a Java application that use Java Collections effectively. First, generate

ID: 3650443 • Letter: D

Question

Design a Java application that use Java Collections effectively. First, generate 100 random Integers between 1 and 49 and write them in a text file named boy.txt, one number per line.

Then read the 100 Integers from the boy.txt text file and place them into a Java collection. The application should then (in this order):

- eliminate duplicates

- sort the collection

- display the sorted collection on the screen

Be sure your code compiles and runs as expected. Name your Java file nani.java. Capture a screenshot of your program's output,

Explanation / Answer

Please rate...

Program nani.java

=======================================================

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;

class nani
{
    public static void main(String args[])
    {
        int a,i;
        Random r=new Random();
        try
        {
            FileWriter fstream = new FileWriter("boy.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            for(i=0;i<100;i++)
            {
                a=r.nextInt(48)+1;
                out.write(a+" ");
            }
            out.close();
        }catch (Exception e)
        {
            System.err.println("Error: " + e.getMessage());
        }

        File infile;
        Scanner inFile = null;
        ArrayList<Integer> arr1=new ArrayList<Integer>();
        try
        {
            infile=new File("boy.txt");
            inFile=new Scanner(infile);
        }
        catch(FileNotFoundException e)
        {
            System.out.println("File does not exist, try again!!");
        }
        while(inFile.hasNextLine())
        {
            String t=inFile.nextLine();
            int a1=Integer.parseInt(t);
            arr1.add(a1);
        }

        int j;
        for(i=0;i<arr1.size()-1;i++)
        {
            for(j=i+1;j<arr1.size();j++)
            {
                if(arr1.get(i).equals(arr1.get(j)))arr1.remove(j);
            }
        }


        Integer ar[]= new Integer[arr1.size()];
        arr1.toArray(ar);
        Arrays.sort(ar);
        arr1.clear();
        arr1.addAll(Arrays.asList(ar));



        System.out.println("The sorted collection: ");
        for(i=0;i<arr1.size();i++)
        {
            if(i!=arr1.size()-1)System.out.print(arr1.get(i)+", ");
            else System.out.print(arr1.get(i));
            if((i+1)%10==0)System.out.println();

        }
    }
}

=========================================================

Sample output: