Alex Alex - 1 month ago 11
Java Question

How to only get one output from a loop when testing a HashSet

I am building a program which is supposed to tell if a list of words from a text file are all unique or if there is a duplicate using a HashSet. If there is a duplicate, the only output should be "UNIQUE", and if there are no duplicates, the output should be "NOT_UNIQUE".

I believe the way to do this is to add the words from the file to the HashSet, and if a word can't be added it is because that word is a duplicate. I have already started building the program, but the program outputs "UNIQUE" for every word as opposed to just once at the end of the program. I think this has to do with my use of a while-loop and infile.readLine(), but I'm not sure what else to do here. Thank you for your help. My code is below:

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

public class Lab5
{
public static void main (String[] args) throws Exception
{
HashSet<String> set = new HashSet<String>();
BufferedReader infile = new BufferedReader( new FileReader( args[0] ) );
while ( infile.ready() )
{
String word = infile.readLine();
if ( !set.add(word) )
System.out.println("NOT_UNIQUE \n");
else
System.out.println("UNIQUE \n");
}
}
}

Answer

Flags aren't elegant, but in this case I think it's a pragmatic solution. You can set a flag and bail out of the loop if you don't want it to display for every word:

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

public class Lab5
{
    public static void main (String[] args) throws Exception
    {
        boolean isUnique = true;
        HashSet<String> set = new HashSet<String>();
        BufferedReader infile = new BufferedReader( new FileReader( args[0] ) );
        while ( infile.ready() ) 
        {
            String word = infile.readLine();
            if ( !set.add(word) ) {
                isUnique = false;
                break;
            }
        }

        System.out.println(isUnique ? "UNIQUE \n" : "NOT_UNIQUE \n");

    } 
}

Remember to close out your file descriptor if you put this into an application.

Comments