Advertisement
ShadowZek

Untitled

Feb 1st, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Showcase extends Prize {
  5. public static final String FILE_NAME = "./prizeList.txt";
  6. public static final String DELIM = "\t";
  7. public static final int PRIZE_COUNT = 50;
  8. public static final int MAX_PRIZE_COUNT = 5;
  9. public static final int FIELD_AMT = 2;
  10. //Instance variable
  11. private Prize[] prizeList;
  12. //Default constructor, sets the array to the appropriate size and reads the specified file
  13. public Showcase()
  14. {
  15. readFile(FILE_NAME);
  16. }
  17. //Method to select 5 random prizes from the list
  18. public Prize[] choosePrizes()
  19. {
  20. Random r = new Random();
  21. Prize[] chosen = new Prize[MAX_PRIZE_COUNT];
  22. for (int i = 0; i < MAX_PRIZE_COUNT; i++)
  23. {
  24. int rando = r.nextInt(PRIZE_COUNT) % 50;
  25. chosen[i] = prizeList[rando];
  26. }
  27. return chosen;
  28. }
  29. //Reading the file of prizes.
  30. public static Prize[] readFile(String fileName)
  31. {
  32. try
  33. {
  34. Scanner fileScanner = new Scanner(new File(fileName));
  35. //Counts the number of prizes
  36. int count = 0;
  37. while(fileScanner.hasNextLine())
  38. {
  39. count++;
  40. fileScanner.nextLine();
  41. }
  42. String fileLine;
  43. String[] splitLines;
  44. Prize[] readPrize = new Prize[count];
  45. //Reset the Scanner
  46. fileScanner = new Scanner(new File(fileName));
  47. //Reads the prizes
  48. int prizeCount = 0;
  49. while(fileScanner.hasNext())
  50. {
  51. fileLine = fileScanner.nextLine();
  52. splitLines = fileLine.split(DELIM);
  53. if(splitLines.length == FIELD_AMT)
  54. {
  55. String name = splitLines[0];
  56. int price = Integer.parseInt(splitLines[1]);
  57. readPrize[prizeCount] = new Prize(name, price);
  58. prizeCount++;
  59. }
  60. }
  61. fileScanner.close();
  62. return readPrize;
  63. }
  64. catch(IOException e)
  65. {
  66. System.out.println(e);
  67. }
  68. catch(Exception e)
  69. {
  70. System.out.println(e);
  71. }
  72. return null;
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement