Education games Production software Strategy Technology

Coding A Raffle List Editor in Java Using ArrayList

One night in the summer while looking over my decent game collection which you may have seen in the background of one of my “Video Game Sheriff” series videos, while having trouble deciding which of the many great games I wanted to play in that moment, I was inspired to write a program that could work like a hat where I could put in the titles of all my games then select one out at random.

You can get a glimpse of my collection in the background of some of my videos also posted on this site.

The resultant application is a console based editor which allows the user to build his own list of titles, edit them, delete them individually, clear them all, save them to a text file as well as read the text file made (or imported to the folder) prior to running the program.

I’m going to go through each part of the code and explain why I made the choices I did. I hope this can provide a good reference or template for your java projects.

My main method for accomplishing the editor and raffle program was centered around the use of arraylist along with some basic IO work. Let’s dive right in:

First I imported the libraries I thought I might need (you can figure this out as you go along of course)

import java.util.*;
import java.io.*;
import java.nio.file.*;

Variables

I decided to write this procedurally as one class since this is not a huge complex program being developed in a massive organization. I called my main class “Interface” but you can choose any name you want for yours. I decided to make a unique scanner object for each part of the program, but this may not be necessary in your project. I have laid out all the variables I used, though you may get by on more or less variables, considering the structure of my app, it will need to use at least one arraylist to function. Note that I use a Random class from the library in order to generate a random seed for the raffle feature.

public class Interface {
    public static void main(String[] args) throws IOException {
        Scanner selection = new Scanner(System.in);
        Scanner input = new Scanner(System.in);
        Scanner in = new Scanner(System.in);
        Scanner edit = new Scanner(System.in);
        int currentChoice = 0;
        String currentGame = "null";
        ArrayList<String> games = new ArrayList<String>();
        Random raffleWheel = new Random();
        String userEdit = "null";
        int gameIndex = 0;
        int gameIndex4D = 0;

Menu LOOP

The top of my program begins with a welcome message and a menu in a while loop along with an input scanner object awaiting user input based on selecting from the menu (loop closes at end of program shown at end of article). Note that because choices 8 & 9 exit the program, I made that as the loop condition.

System.out.println("Welcome to the Backlog Gaming Sheriff's Super Raffler!\n");
    while (currentChoice <= 7 || currentChoice >= 10){

        System.out.println("\n1. Run the Raffler and make a random selection.");
        System.out.println("2. View game list");
        System.out.println("3. Add new game to the list");
        System.out.println("4. Delete a game from the list");
        System.out.println("5. Edit a game on the list");
        System.out.println("6. Clear Game List");
        System.out.println("7. Read Game List");
        System.out.println("8. Quit & Save List");
        System.out.println("9. Quit without saving\n");
        System.out.println("Please make a selection from the above options");
        currentChoice = selection.nextInt();

Conditional Statements

Next up are the conditional statements that serve as the engine of the program. I first start with a potentially erroneous input, beyond the menu choices.

if (currentChoice > 9){
    System.out.println("Error. Invalid input. Please try again.\n");
}

My next conditional statement is for choice #7 from the menu to read the game list, as that is often the first thing the user may need to do.

else if (currentChoice == 7){
     try (BufferedReader br = new BufferedReader(new FileReader("Game_List.txt"))) {
     String line;
     while ((line = br.readLine()) != null) {
         games.add(line);
      }
   }
}

The following conditional statement allows the user to delete a title from the list while providing the option to confirm or cancel the deletion of that item (more fail safe than C!) and provides the template for other options requiring submenu options. Note my use of ArrayList class’s ‘size’ function to determine the length of the array to base the validity of the index number on.

else if (currentChoice == 4){
    int counter = 1;
    while (counter != 0){
        System.out.println("\nPlease enter game index number");
        gameIndex4D = in.nextInt();
        if (gameIndex4D > games.size()){
            System.out.println("\nError. Invalid index number.");
        }
        else if (gameIndex4D < 0){
            System.out.println("\nError. Invalid index number.");
        }
        else
        counter = 0;
        }
        System.out.println("\nThe selected game title currently is:");
        System.out.println(games.get(gameIndex4D));
        System.out.println("\nAre you sure you want to delete the selected title?");
        System.out.println("1. Confirm");
        System.out.println("2. Cancel");
        int userChoice = in.nextInt();
        if (userChoice == 1){
            games.remove(gameIndex4D);
            System.out.println("Selected title deleted.");
        }
        else if (userChoice == 2 || userChoice < 1 || userChoice >2){
            System.out.println("Deletion Canceled.");
        }
     }

A simpler version of the above condition, allows the user to clear the entire list from the program (but not the file).

else if (currentChoice == 6){
    System.out.println("\nAre you sure you want to delete all titles?");
    System.out.println("1. Confirm");
    System.out.println("2. Cancel");
    int userChoice = in.nextInt();
    if (userChoice == 1){
        while (games.size() > 0){
            games.remove(games.size()-1);
        }
        System.out.println("Game list cleared.");
     }
     else if (userChoice == 2 || userChoice < 1 || userChoice >2){
         System.out.println("Deletion Canceled.");
     }
}

To add a title, I simply used ArrayList class’s ‘add’ function.

else if (currentChoice == 3){
    System.out.println("\nPlease enter game name");
    currentGame = input.nextLine();
    games.add(currentGame);
 }

In order to list out every title in the ArrayList for the user, I wrote a simple for loop to handle that task for each item in the list, printed with print line.

else if (currentChoice == 2){
    for (int i=0;i<(games.size());i++){
        System.out.println(games.get(i));
    }
}

The conditional statement after that handles the actual raffle feature, randomly selecting one title from the entire list.

else if (currentChoice == 1){
    System.out.println("Running Raffler\n");
    for (int i=1;i<4;i++){
        System.out.print(".");
    }
    int raffleNum = raffleWheel.nextInt(games.size());
    String raffleGame = games.get(raffleNum);
    System.out.println("\n" + raffleGame);
}

Once again using the submenu template I wrote for the delete option, this condition was developed to allow the user to change the name of a title he already added based on the index number (with title 1 starting at index 0, title 2 at index 1, etc…).

else if (currentChoice == 5){
    int counter2 = 1;
    while (counter2 != 0){
    System.out.println("\nPlease enter game index number");
    gameIndex = in.nextInt();
    if (gameIndex > games.size()){
        System.out.println("\nError. Invalid index number.");
    }
    else if (gameIndex < 0){
        System.out.println("\nError. Invalid index number.");
    }
    else
        counter2 = 0;
    }
    System.out.println("\nThe selected game title currently is:");
    System.out.println(games.get(gameIndex));
    System.out.println("\nPlease enter replacement title:");
    userEdit = edit.nextLine();
    games.set(gameIndex, userEdit);
}

For the quit and save option, I use a try/catch structure as the standard to prevent the IO process from having any problems. This code successfully writes the current program’s ArrayList to a designated text file in the program folder.

if (currentChoice == 8){
    System.out.println("Goodbye!");
    try{
        PrintWriter gameList = new PrintWriter("Game_List.txt");
        for (int i=0;i<(games.size());i++){
            gameList.println(games.get(i));
        }
        gameList.close();
        }
    catch (Exception ex) {
        ex.printStackTrace();
    }
}

End Of The Program

I end off the program with a simple goodbye message and the necessary closing braces to close out the while loop, main class and surrounding “Interface” class.

            if (currentChoice == 9){
                System.out.println("Goodbye!");
            }
        }
    }
}

Feel free to copy and paste all the above code in order to an appropriately named class and run it for yourself. Hopefully this can help you on your journey to learn Java or in your working project.

SPONSORED: 20% OFF PREMIUM WORDPRESS HOSTING THROUGH PRODUCTION HACKERS

Related Posts