James Liang - ICS Blog

ICS4U Blogging

FileIO - Multiplayer Coding

Multiplayer Coding

Main.java

/*
Create a program to read from a flat file and write to the flat file. You will create a menu for reading and writing to the file. Use the folllowing starter code.
*/
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileWriter;

class Main {
  public static void main(String[] args) throws IOException{
    int length = databaseLength();
    String[][] database = parseDatabase(length);
    String choice = menu();
    selection(choice, length, database);
  }
  public static int databaseLength() throws IOException {
    int lineNumber = 0;
    try{
      Scanner fileInput = new Scanner(new File("database.txt"));
      while (fileInput.hasNext()) {
        lineNumber++;
        fileInput.nextLine();
      }
      fileInput.close();
    }catch (IOException ioException) {
      System.err.println("Java Exception: " + ioException);
    }
    return lineNumber;
  }
  public static String[][] parseDatabase(int length) throws IOException {
    String[][] databaseParsed = new String [length][4];
    int line = 0; 
    try {
      Scanner fileInput = new Scanner(new File("database.txt"));
      while (fileInput.hasNext()) {
        String output = fileInput.nextLine();
        String[] info = output.split(",");
        databaseParsed[line][0] = info[0].trim();
        databaseParsed[line][1] = info[1].trim();
        databaseParsed[line][2] = info[2].trim();
        databaseParsed[line][3] = info[3].trim();
        line++;
      }
    } catch (IOException ioException) {
      System.err.println("Java Exception: " + ioException);
    }
    return databaseParsed;
  }
  public static String menu() {
    System.out.println("Main menu:");
    System.out.println("a)  Show all last names");
    System.out.println("b)  Show all first names");
    System.out.println("c)  Show all date of births");
    System.out.println("d)  Show all student numbers");
    System.out.println("e)  Enter a new student");
    System.out.print("Enter your choice: ");
    Scanner input = new Scanner (System.in);
    String choice = input.nextLine();
    return choice;
  }
  public static void selection(String choice, int length, String[][] database) {
    if (choice.equalsIgnoreCase("a")) {
      for (int i = 1; i < length; i++) {
        System.out.println(database[i][0]);
      }
    }
    else if (choice.equalsIgnoreCase("b")) {
      for (int i = 1; i < length; i++) {
        System.out.println(database[i][1]);
      }
    }
    else if (choice.equalsIgnoreCase("c")) {
      for (int i = 1; i < length; i++) {
        System.out.println(database[i][2]);
      }
    }
    else if (choice.equalsIgnoreCase("d")) {
      for (int i = 1; i < length; i++) {
        System.out.println(database[i][3]);
      }
    }
    else if (choice.equalsIgnoreCase("e")) {
      Scanner input = new Scanner (System.in);
      String last;
      String first;
      String dob;
      String stuNum;
      System.out.print("Enter last name: ");
      last = input.nextLine();
      System.out.print("Enter first name: ");
      first = input.nextLine();
      System.out.print("Enter date of brith: ");
      dob = input.nextLine();
      System.out.print("Enter student number: ");
      stuNum = input.nextLine();
      try{
        FileWriter myWriter = new FileWriter("database.txt", true);
        myWriter.write("\n" + last + ", " + first + ", " + dob + ", " + stuNum);
        myWriter.close();
        System.out.println("Sucessfully wrote to file");
      }catch (IOException e) {
        System.out.println("An error occured ):");
        e.printStackTrace();
      }
    }
  }
}

database.txt

Lname, Fname, DoB, Student #
Amlani, Omar, 09/12/1999, 123321231
Singh, Amardeep, 11/24/2001, 789321931
David, Robin, 10/12/2001, 123543234
Lam, Lisa, 09/12/2000, 789654456
Persad, Cheryl, 08/31/1999, 971340234
Peraud, Kamita, 03/06/2001, 976876567
Luu, Kien, 20/07/1999, 973987234
Smith, John, 10/03/2000, 345653823

Post on your Learning Blog with a DETAILED EXPLANATION of your code, try to use all the programming TERMINOLOGY from this topic

First, I had to import everything that I’d need to use in the program. I then created my class and main method. The method throws IOException as sometimes without it, the program would cease to function. Inside the main method, I call three methods and set three variables to the returned result. I then call a fourth method passing through the newly created variables.

The next method I created was the databaseLength method. This method takes no parameters and returns an int. It also throws an IOException and it’s dealing with files. I created an integer variable and set it to zero. I then created try and catch block, in the try block I created a new Scanner and utilized a while loop to keep going through the file as long as there was data on the next line. Inside the loop, I increased the integer variable by one. After the loop finished, I closed the file. The catch block would errors and print them out. Finally, I returned the integer variable.

The next method is the parseDatabase method. It takes an integer parameter and names it length, it also returns a 2D String array. Utilizing the length variable, I created a new 2D array, I used a four for the columns as I knew how many columns there would be. I then created an integer variable called line and set it to zero. A try and catch block was used again to read the file. Inside the try block, I created a new Scanner and used a while loop similar to the previous method. I set a String array to the the split version of a line. Since the values in the line were separated by commas I could split by “,”. I then started setting values from the new String array to the 2D array. I used trim since there could’ve been blank spaces. I then increased the line variable by one and kept looping until I was done with all the students.

The next method is the menu method. It’s a short method that takes no parameters and returns a String. It prints out all the menu options and utilizes a Scanner to read the user’s input. It then returns that String input.

The final method is the selection method. It has three parameters and returns nothing. The choice parameter is used to find out what the program needs to do. The first four if and else if statements are choices a to d. These are just listing items from the file, so I used a for loop to go through everything in that specific column. The final else if statement is for adding a new student. I created a new Scanner and String variables for the new student. I then prompted the user for each of the new values. After all the values were inputted, I used a try and catch block to write to a the file. In the try block, I used FileWriter, I added true when working with FileWriter as I didn’t want to overwrite the file. I then wrote the data onto a new line with commas to separate the values like the other lines. After that, I closed the file and outputted a confirmation message to confirm that the data was written to the file. The catch block would catch any errors that occured.