Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class Showcase extends Prize {
- public static final String FILE_NAME = "./prizeList.txt";
- public static final String DELIM = "\t";
- public static final int PRIZE_COUNT = 50;
- public static final int MAX_PRIZE_COUNT = 5;
- public static final int FIELD_AMT = 2;
- //Instance variable
- private Prize[] prizeList;
- //Default constructor, sets the array to the appropriate size and reads the specified file
- public Showcase()
- {
- prizeList = new Prize[PRIZE_COUNT];
- readFile(FILE_NAME);
- }
- //Method to select 5 random prizes from the list
- public Prize[] choosePrizes()
- {
- Random r = new Random();
- Prize[] chosen = new Prize[MAX_PRIZE_COUNT];
- for (int i = 0; i < MAX_PRIZE_COUNT; i++)
- {
- int rando = r.nextInt(PRIZE_COUNT);
- chosen[i] = prizeList[rando];
- }
- return chosen;
- }
- //Reading the file of prizes.
- public static Prize[] readFile(String fileName)
- {
- try
- {
- Scanner fileScanner = new Scanner(new File(fileName));
- //Counts the number of prizes
- int count = 0;
- while(fileScanner.hasNextLine())
- {
- count++;
- fileScanner.nextLine();
- }
- String fileLine;
- String[] splitLines;
- Prize[] readPrize = new Prize[count];
- //Reset the Scanner
- fileScanner = new Scanner(new File(fileName));
- //Reads the prizes
- int prizeCount = 0;
- while(fileScanner.hasNext())
- {
- fileLine = fileScanner.nextLine();
- splitLines = fileLine.split(DELIM);
- if(splitLines.length == FIELD_AMT)
- {
- String name = splitLines[0];
- int price = Integer.parseInt(splitLines[1]);
- readPrize[prizeCount] = new Prize(name, price);
- prizeCount++;
- }
- }
- fileScanner.close();
- return readPrize;
- }
- catch(IOException e)
- {
- System.out.println(e);
- }
- catch(Exception e)
- {
- System.out.println(e);
- }
- return null;
- }
- }
Add Comment
Please, Sign In to add comment