this code was suppose to prevent any single line from appearing twice for each display, i thought it was ok but later found that it wasnt, i was directed to use the hashset method in combination with my code to prevent that from happening, but it is not consistent, i need a solution to this please

import java.io.*;         
import java.util.*;
class RandomSelection {




        
    public static void main(String[] args) {    

try{
        FileInputStream  fstream = new FileInputStream("c:\\filea.txt");
    	
         DataInputStream in = new DataInputStream(fstream);
        BufferedReader  br = new BufferedReader(new InputStreamReader(in));
  	LineNumberReader  ln = new LineNumberReader(br);

      	int count = 0;

    	while (ln.readLine() != null){

    		count++;
	}
	ln.close();
	in.close();
     

      
	fstream = new FileInputStream("c:\\filea.txt");

    	in = new DataInputStream(fstream);
        br = new BufferedReader(new InputStreamReader(in));
    	String strLine;
  	ln = new LineNumberReader(br);
        Random mixture = new Random();
        HashSet<Integer> usedNums = new HashSet<Integer>();

        int numberIndex;
		String[] see = new String[count];
 		int i = 0;

	  while ((strLine = br.readLine()) != null)   {



			see[i] = strLine;

	              i = i + 1;
          }
                           for ( i=1; i <=5; i++) {
                           do{numberIndex = mixture.nextInt(see.length);
                           }

                           while(!usedNums.add(numberIndex) );


                     System.out.println(see[numberIndex]);
                          }


      ln.close();
       in.close();

 }
    catch (Exception e){
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Recommended Answers

All 4 Replies

Ok .. so as you read in items, populate them into a list. But before putting an item in the list, check to see if it is already in the list. If it is, do nothing. Why do you need a hash for that?

how to i do that, please can you give me an instance

well... you could store them in a Vector
just use the contains(Object test) method to check whether or not it's allready in your list, if so, do nothing, if not, add
and when your list is complete, write it

how to i do that, please can you give me an instance

he's told you all you should need to know to implement it.
Turning that into sourcecode is your job, it's also rather trivial.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.