Search code examples
javajgrasp

java program to read text file and output with out duplicate? loop to skip duplicate line


I was suppose to read text file and display original file and output file without any duplicate line.

import java.io.*;
import java.util.Scanner;

public class questionOne {


    public static void main(String args[]) throws FileNotFoundException  {

        FileInputStream fis = new FileInputStream("text.txt");
        Scanner scanner = new Scanner(fis);


        System.out.println("ORIGINAL FILE: input.txt contains the values   ");


        while(scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }

        scanner.close();

        System.out.println("OUTPUT FILE: output.txt contains the values");

        // String a = 

    }   
}

Solution

  • You need to use a Set structure to do this. Instead of displaying what you have read, store it, and print the set.

    Use this method:

    Set<String> uniqueLines = new TreeSet<>();
    //in a loop
    uniqueLines.add(scanner.nextLine();
    // display the set
    

    Since this is a homework question, I won't give the whole answer. Good luck with your code :)