Answer to Question #204607 in Java | JSP | JSF for seraj

Question #204607

Write a program that reads a file of numbers of type int and writes all the numbers to another file, but without any duplicate numbers.Assume that the numbers in the input file are already ordered from smallest to largest. 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

1
Expert's answer
2021-06-08T23:47:49-0400
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;


public class Numbers {
   public static void main(String[] args) throws Exception {
      //check if source file exists
      File number = new File("Numbers.txt");
      File sorted = new File("Sorted.txt");
      if (!number.exists()) {
         try ( // create the file
         PrintWriter output = new PrintWriter(number);
         ) {
            for (int i = 0; i <= 100; i++) {
               output.print(((int)(Math.random() * 999) + 1) + " ");
            }
         }
      }
      try (
      Scanner input = new Scanner(number);
      ) {
         int[] numbers = new int[100];
         for (int i = 0; i < 100; i++) {

             numbers[i] = input.nextInt();           
         }
        if (!sorted.exists()) {
           try (
           PrintWriter output = new PrintWriter(sorted)
           ) {
              Arrays.sort(numbers);
              for (int i = 0; i < 100; i ++) {
                 output.print(numbers[i] + " ");
              }
        }
     }
  }
} }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS