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

Write a JAVA program that reads a file of numbers of type int and outputs all th

ID: 642575 • Letter: W

Question

Write a JAVA program that reads a file of numbers of type int and outputs all the numbers to another file, but without any duplicate numbers. Assume that the input file is sorted from smallest first to largest last. After the program is run, the new file will contain all the numbers in the original file, but no number will appear more than once in the file. The numbers in the output file should also be sorted from smallest to largest. Your program should obtain both file names from the user. Use a text file that stores one number per line.

Explanation / Answer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;

public class FileNumbers {
  
   public static boolean findNumber(int arr[], int count, int num){
       for(int i = 0; i < count; ++i){
           if(arr[i] == num){
               return true;
           }
       }
       return false;
   }
  
   public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       int arr[] = new int[1000];
       int num;
       int count = 0;
       System.out.print("Enter Input file name: ");
       String inputFile = in.nextLine();
       System.out.print("Enter output file name: ");
       String outputFile = in.nextLine();
       try {

           BufferedReader br = new BufferedReader(new FileReader(inputFile));
           String strLine;
           // Read File Line By Line
           while ((strLine = br.readLine()) != null) {
               String StringArr[] = strLine.split(" ");
               for(int i = 0; i < StringArr.length; ++i){
                   num = Integer.parseInt(StringArr[i]);
                   if(findNumber(arr, count, num) == false){
                       arr[count++] = num;
                   }
               }
           }
           BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
           for(int i = 0; i < count; ++i){
               bw.write(Integer.toString(arr[i]) + " ");
           }
           bw.close();
           br.close();
       } catch (Exception e) {// Catch exception if any
           System.err.println("Error: " + e.getMessage());
       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote