ShadowZek

Untitled

Jan 31st, 2019
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 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. prizeList = new Prize[PRIZE_COUNT];
  16. readFile(FILE_NAME);
  17. }
  18. //Method to select 5 random prizes from the list
  19. public Prize[] choosePrizes()
  20. {
  21. Random r = new Random();
  22. Prize[] chosen = new Prize[MAX_PRIZE_COUNT];
  23. for (int i = 0; i < MAX_PRIZE_COUNT; i++)
  24. {
  25. int rando = r.nextInt(PRIZE_COUNT);
  26. chosen[i] = prizeList[rando];
  27. }
  28. return chosen;
  29. }
  30. //Reading the file of prizes.
  31. public static Prize[] readFile(String fileName)
  32. {
  33. try
  34. {
  35. Scanner fileScanner = new Scanner(new File(fileName));
  36. //Counts the number of prizes
  37. int count = 0;
  38. while(fileScanner.hasNextLine())
  39. {
  40. count++;
  41. fileScanner.nextLine();
  42. }
  43. String fileLine;
  44. String[] splitLines;
  45. Prize[] readPrize = new Prize[count];
  46. //Reset the Scanner
  47. fileScanner = new Scanner(new File(fileName));
  48. //Reads the prizes
  49. int prizeCount = 0;
  50. while(fileScanner.hasNext())
  51. {
  52. fileLine = fileScanner.nextLine();
  53. splitLines = fileLine.split(DELIM);
  54. if(splitLines.length == FIELD_AMT)
  55. {
  56. String name = splitLines[0];
  57. int price = Integer.parseInt(splitLines[1]);
  58. readPrize[prizeCount] = new Prize(name, price);
  59. prizeCount++;
  60. }
  61. }
  62. fileScanner.close();
  63. return readPrize;
  64. }
  65. catch(IOException e)
  66. {
  67. System.out.println(e);
  68. }
  69. catch(Exception e)
  70. {
  71. System.out.println(e);
  72. }
  73. return null;
  74. }
  75. }
Add Comment
Please, Sign In to add comment