fork download
  1. import java.util.Arrays;
  2. import java.util.TreeSet;
  3. import java.util.Random;
  4.  
  5. class Example {
  6. public static void main(String[] args) {
  7. int min = 1;
  8. int max = 49;
  9. int total = 6;
  10.  
  11. // TreeSet's are always sorted, but slightly slower than HashSets
  12. // Another option is to use a hashset, convert to a list then sort
  13. TreeSet<Integer> numbers = new TreeSet<Integer>();
  14.  
  15. Random r = new Random();
  16. for(int i = 0; i < total; ++i) {
  17. int n;
  18. do {
  19. n = r.nextInt(max - min + 1) + min;
  20. } while(!numbers.add(n));
  21.  
  22. /* Or if you like confusing code:
  23.   while(!numbers.add(r.nextInt(max - min + 1) + min));
  24.   */
  25.  
  26. }
  27. System.out.print("Your Lucky Numbers Are ");
  28. for(int number : numbers) {
  29. System.out.print(number + " ");
  30. }
  31. System.out.println();
  32. }
  33. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
Your Lucky Numbers Are 12 15 24 26 33 39