Java 2

Week 2

Topic this Week

  • CSV file input
  • Streams
  • Functional Interfaces
  • Method References

BPA State Competition

  • Open the 2024 Java competition file.
  • Open VS Code. Close your project from last week.
  • From page 3: "Create a folder on the flash drive provided using your contestant number as the name of the folder"​
    • Create a new Java project with no build tools.
    • Title it "JAVA-KNNNNNNN"
  • From page 3: "Copy your entire solution/project into this folder. The project folder has already been provided for you : Java_State"
  • Please note that the directions and starter code are created by a volunteer; don't get frustrated with typos.
  • Read the remaining directions on pages 3-4 and rubric on page 9.
    • The directions on pages 3-4 are consistent from year to year.
    • Read the rubric on page 8 as you go.

Update Starter Code

  • Inspect the provided Java code. Note that only one class is declared public
  • Change the "Students" class to "Student". Rename the constructors. Update the class name on lines 39, 63, and 72.
    • I think it will make the program easier to understand
  • Create a static List<Student> object in the SeatingChartBuilderState class.
  • Line 93 says, "Create appropriately variables based upon constructor parameters"
  • Update the parameterized constructor and getter methods.
  • Format the code by pressing Shift + Alt + F
  • You can make other adjustments like moving the Student class to a separate file, but it is not necessary.
  • Your code will look like the example on the next slide.
    • This code includes the first 3 comments (See page 9).
/**
 * Contestant number: KNNNNNNN
 */
 
import java.io.FileNotFoundException;
import java.io.File;
import java.util.*;
import java.text.DecimalFormat;

public class SeatingChartBuilderState {

   //SC2 Create Scanner and ArrayList objects
   private static Scanner scanner = new Scanner(System.in);
   private static List<Student> students = new ArrayList<>();

   public static void main(String args[]) {

      inputManager();

      printStudents();
      printHighestGPA();
      printLowestGPA();

   }

   // Finds and prints the highest GPA from all the students
   private static void printHighestGPA() {

   }

   // Finds and prints the lowest GPA from all the students
   private static void printLowestGPA() {

   }

   private static void setStudents(int nc) {
      Random rand = new Random();
      Student s;
      DecimalFormat df = new DecimalFormat("#.00");
      int nameCount = nc;
      double gpa;
      int grade;
      String fn;
      String ln;

      String[] allNames = { "Walter", "Jones", "Rose", "Wilson", "Jack", "Rodriguez", "Elizabeth", "Smith", "Earl",
            "Carter", "Linda", "Ward", "Christopher",
            "Turner", "Martin", "Murphy", "Betty", "Garcia", "Shawn", "Taylor", "Sean", "Simmons", "Joshua", "Evans",
            "Norma", "Mitchell", "Brenda", "Johnson", "Donna",
            "Clark", "Irene", "Diaz", "Marilyn", "Coleman", "Arthur", "Collins", "Henry", "Hall", "Howard", "Robinson",
            "Jerry", "Green", "Maria", "Price", "Evelyn", "Bell",
            "Janet", "Moore", "Susan", "Foster" };

      for (int i = 0; i < nameCount; i++) {

         do {

            fn = allNames[rand.nextInt(allNames.length)];
            ln = allNames[rand.nextInt(allNames.length)];
         } while (fn.equals(ln));
         grade = rand.nextInt(4) + 9;
         double tempGPA = rand.nextDouble() * 3.0 + 1.0;
         String tempString = df.format(tempGPA);
         gpa = Double.parseDouble(tempString);
         s = new Student(fn, ln, grade, gpa);
         students.add(s);
      }

   }

   // Given
   private static void printStudents() {
      int i = 1;
      for (Student n : students) {
         System.out
               .println(i + ") " + n.getWholeName() + " | Grade Level: " + n.getGradeLevel() + " | GPA: " + n.getGPA());
         i++;
      }

      printHighestGPA();
      printLowestGPA();
   }

   // Gets user input commands and checks for entry errors
   private static void inputManager() {

   }

}

//SC1 All constructors, methods, and variables are appropriately created.
class Student {
   // Create appropriately variables based upon constructor parameters
   private String firstName;
   private String lastName;
   private int gradeLevel;
   private double gpa;

   // Generic Constructor
   public Student() {

   }

   // Constructor with Parameters
   public Student(String fn, String ln, int gl, double gpa) {
      this.firstName = fn;
      this.lastName = ln;
      this.gradeLevel = gl;
      this.gpa = gpa;
   }

   // Returns "last name, first name" with appropriate variables
   public String getWholeName() {
      return String.format("%s, %s", lastName, firstName);
   }

   // Returns first name
   public String getFirstName() {
      return firstName;
   }

   // Returns last name
   public String getLastName() {
      return lastName;
   }

   // Returns the GPA
   public double getGPA() {
      return gpa;
   }

   // Returns grade level
   public int getGradeLevel() {
      return gradeLevel;
   }

}

Input Option 1, Step 1

  • This project is a menu-based program, similar to the final project in Java 1.
  • Read the directions starting on page 5. Do one step at a time.
  • For step 1, use the inputManager method. As you complete each step, I recommend completing the required error messages. 
  • Try to make your output as close to the example as possible.
  • Add comments as you go.
  • Keep only the inputManager() function call in the main method or option 3 will cause an error.
  • Your code may look like the example on the next slide.
    • What do you remember from Java 1?
// Gets user input commands and checks for entry errors
private static void inputManager() {
   Scanner scanner = new Scanner(System.in);
   loop: while(true) {
      System.out.println("\n---------------------------------------------------------------------");
      System.out.println("Hello. What would you like to do today?");
      System.out.println("Press [1] to create random students OR Press [2] to create a single student OR Press [3] to end the program");
      int choice = 0;
      // SC5 Code with try/catch exception for invalid data error
      try {
         choice = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }
	
      switch(choice) {
         case 1:
            break;
         case 2:
            break;
         case 3:
            break loop;
         default:
            // SC5 Code for range violation
            System.out.println("Your entry is out of range.");
      }
   }
   System.out.println("Goodbye!");
}

Input Option 1, Step 2

  • Consider creating your own helper methods to organize your code.
  • Create a method called step2 that has no inputs and returns an int.
  • Write code to handle the instructions and error messages.
  • Add comments as you go.
  • Your code may look like the example on the next slide.
    • What do you remember from Java 1?
    • In Java 1, we passed the Scanner object as an argument to helper methods. This is required if you split your project into multiple packages and files.
// Gets user input commands and checks for entry errors
private static void inputManager() {
   Scanner scanner = new Scanner(System.in);
   loop: while(true) {
      System.out.println("\n---------------------------------------------------------------------");
      System.out.println("Hello. What would you like to do today?");
      System.out.println("Press [1] to create random students OR Press [2] to create a single student OR Press [3] to end the program");
      int choice = 0;
      // SC5 Code with try/catch exception for invalid data error
      try {
         choice = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }

      switch(choice) {
         case 1:
            int numStudentsToCreate = option1Step2();
            break;
         case 2:
            break;
         case 3:
            break loop;
         default:
            // SC5 Code with try/catch exception for invalid data error
            System.out.println("Your entry is out of range.");
      }
   }
   System.out.println("Goodbye!");
}

private static int option1Step2() {
   int val = 0;
   loop: while(true) {
      System.out.print("\nPlease enter in a value between 1 and 50: ");
      // SC6 Code with try/catch exception for invalid data error
      try {
         val = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }
      // SC6 Code for range violation
      if(val < 1 || val > 50) {
         System.out.println("Your entry is out of range.");
         continue;
      }
      break;
   }
   return val;
}

Input Option 1, Step 3

  • Create a new method called step3 that takes an int as input and returns void.
  • Use the value returned from the step 2 method when calling the step3 method.
  • Write code to handle the instructions. In situations like this, call methods that already exist.
  • Implement the printHighestGPA and printLowestGPA methods.
  • Add comments as you go.
  • Your code may look like the example on the next slide.
    • What do you remember from Java 1?
    • Later we will improve the methods that calculate the highest and lowest GPAs.
  • This is probably where I would expect most students to get in 90 minutes.
// SC3: Finds and prints the highest GPA from all the students
private static void printHighestGPA() {
   Student highestGPA = students.get(0);
   for(Student student: students) {
      if(student.getGPA() > highestGPA.getGPA()) {
         highestGPA = student;
      }
   }
   System.out.printf("\n\nMax GPA: %.2f %s, %s\n", highestGPA.getGPA(), highestGPA.getLastName(), highestGPA.getFirstName());
}

// SC4: Finds and prints the lowest GPA from all the students
private static void printLowestGPA() {
   Student lowestGPA = students.get(0);
   for(Student student: students) {
      if(student.getGPA() < lowestGPA.getGPA()) {
         lowestGPA = student;
      }
   }
   System.out.printf("\n\nMin GPA: %.2f %s, %s\n", lowestGPA.getGPA(), lowestGPA.getLastName(), lowestGPA.getFirstName());
}

// Gets user input commands and checks for entry errors
private static void inputManager() {
   Scanner scanner = new Scanner(System.in);
   loop: while(true) {
      System.out.println("\n---------------------------------------------------------------------");
      System.out.println("Hello. What would you like to do today?");
      System.out.println("Press [1] to create random students OR Press [2] to create a single student OR Press [3] to end the program");
      int choice = 0;
      try {
         choice = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }

      switch(choice) {
         case 1:
            int numStudentsToCreate = option1Step2(scanner);
            option1Step3(numStudentsToCreate);
            break;
         case 2:
            break;
         case 3:
            break loop;
         default:
            System.out.println("Your entry is out of range.");
      }
   }
   System.out.println("Goodbye!");
}

private static void option1Step3(int numStudentsToCreate) {
   setStudents(numStudentsToCreate);
   printStudents();
}

Input Option 2, Steps 2-6

  • Create a method to create a new student.
  • Getting the first name and last name require no validation
  • Getting the gradeLevel and gpa require validation.
  • Add the newly created object to your List. Print the list.
  • Add a line before printing the student list.
  • Your code may look like the example on the next slide.
private static void printStudents() {
   int i = 1;
   System.out.println("\n---------------------------------------------------------------------");
   for (Student n : students) {
      System.out
            .println(i + ") " + n.getWholeName() + " | Grade Level: " + n.getGradeLevel() + " | GPA: " + n.getGPA());
      i++;
   }

   printHighestGPA();
   printLowestGPA();
}

// Gets user input commands and checks for entry errors
private static void inputManager() {
   loop: while(true) {
      System.out.println("\n---------------------------------------------------------------------");
      System.out.println("Hello. What would you like to do today?");
      System.out.println("Press [1] to create random students OR Press [2] to create a single student OR Press [3] to end the program");
      int choice = 0;
      // SC5 Code with try/catch exception for invalid data error
      try {
         choice = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }

      switch(choice) {
         case 1:
            int numStudentsToCreate = option1Step2(scanner);
            option1Step3(numStudentsToCreate);
            break;
         case 2:
            createSingleStudent();
            break;
         case 3:
            break loop;
         default:
            // SC5 Code for range violation
            System.out.println("Your entry is out of range.");
      }
   }
   System.out.println("Goodbye!");
}

private static void createSingleStudent() {
   System.out.println("You are now creating a single student");
   // Option 2, Step 2
   System.out.println("Enter in the first name");
   String firstName = scanner.nextLine();
   // Option 2, Step 3
   System.out.println("Enter in the last name");
   String lastName = scanner.nextLine();
   // Option 2, Step 4
   int gradeLevel = option2Step4();
   // Option 2, Step 5
   double gpa = option2Step5();
   students.add(new Student(firstName, lastName, gradeLevel, gpa));
   printStudents();
}

private static double option2Step5() {
   double gpa = 0;
   while(true) {
      System.out.println("Enter in the GPA in its proper format (#.##)");
      try {
         gpa = scanner.nextDouble();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }
      if(gpa < 0 || gpa > 4) {
         System.out.println("Your entry is out of range.");
         continue;
      }
      break;
   }
   return gpa;
}

private static int option2Step4() {
   int gradeLevel = 0;
   while(true) {
      System.out.println("Enter in the student grade level");
      try {
         gradeLevel = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }
      if(gradeLevel < 9 || gradeLevel > 12) {
         System.out.println("Your entry is out of range.");
         continue;
      }
      break;
   }
   return gradeLevel;
}

Completed Code

// Contestant: K0519415

import java.io.FileNotFoundException;
import java.io.File;
import java.util.*;
import java.text.DecimalFormat;

public class SeatingChartBuilderState {

   // SC2: Create Scanner and ArrayList objects
   private static Scanner scanner = new Scanner(System.in);
   private static List<Students> students = new ArrayList<>();

   public static void main(String args[]) {
      inputManager();
   }


   // SC3: Finds and prints the highest GPA from all the students
   private static void printHighestGPA() {
      if(students.size() == 0) {
         return;
      }
      // Students highest = students.get(0);
      // for(Students student: students) {
      //    if(student.getGPA() > highest.getGPA()) {
      //       highest = student;
      //    }
      // }
      Students highest = students.stream().max(Comparator.comparingDouble(Students::getGPA)).get();
      System.out.println("\n\nMax GPA: " + highest.getGPAStr() + " " + highest.getWholeName());
   }

   // SC4: Finds and prints the lowest GPA from all the students
   private static void printLowestGPA() {
      if(students.size() == 0) {
         return;
      }
      // Students lowest = students.get(0);
      // for(Students student: students) {
      //    if(student.getGPA() < lowest.getGPA()) {
      //       lowest = student;
      //    }
      // }
      Students lowest = students.stream().min(Comparator.comparingDouble(Students::getGPA)).get();
      System.out.println("\n\nMin GPA: " + lowest.getGPAStr() + " " + lowest.getWholeName());
   }

   // Call this method to generate a random list of students
   private static void setStudents(int nc) {
      Random rand = new Random();
      Students s;
      DecimalFormat df = new DecimalFormat("#.00");
      int nameCount = nc;
      double gpa;
      int grade;
      String fn;
      String ln;

      String[] allNames = {"Walter", "Jones", "Rose", "Wilson", "Jack", "Rodriguez", "Elizabeth",
            "Smith", "Earl", "Carter", "Linda", "Ward", "Christopher", "Turner", "Martin", "Murphy",
            "Betty", "Garcia", "Shawn", "Taylor", "Sean", "Simmons", "Joshua", "Evans", "Norma",
            "Mitchell", "Brenda", "Johnson", "Donna", "Clark", "Irene", "Diaz", "Marilyn",
            "Coleman", "Arthur", "Collins", "Henry", "Hall", "Howard", "Robinson", "Jerry", "Green",
            "Maria", "Price", "Evelyn", "Bell", "Janet", "Moore", "Susan", "Foster"};

      for (int i = 0; i < nameCount; i++) {

         do {

            fn = allNames[rand.nextInt(allNames.length)];
            ln = allNames[rand.nextInt(allNames.length)];
         } while (fn.equals(ln));
         grade = rand.nextInt(4) + 9;
         double tempGPA = rand.nextDouble() * 3.0 + 1.0;
         String tempString = df.format(tempGPA);
         gpa = Double.parseDouble(tempString);
         s = new Students(fn, ln, grade, gpa);
         students.add(s);
      }

   }

   // Given
   private static void printStudents() {
      int i = 1;
      System.out.println("\n---------------------------------------------------------------------");
      for (Students n : students) {
         System.out.println(i + ") " + n.getWholeName() + " | Grade Level: " + n.getGradeLevel()
               + " | GPA: " + n.getGPAStr());
         i++;
      }

      printHighestGPA();
      printLowestGPA();
   }

   // Gets user input commands and checks for entry errors
   private static void inputManager() {
      loop: while(true) {
         System.out.println("\n---------------------------------------------------------------------");
         System.out.println("Hello. What would you like to do today?");
         System.out.println("Press [1] to create random students OR Press [2] to create a single student OR Press [3] to end the program");
         int choice = 0;
         // SC5: Code with try/catch exception for invalid data error
         try {
            choice = scanner.nextInt();
         } catch(InputMismatchException e) {
            System.out.println("ERROR: Please enter valid data type");
            continue;
         } finally {
            scanner.nextLine();
         }
      
         switch(choice) {
            case 1:
               int numStudents = option1Step2();
               setStudents(numStudents);
               printStudents();
               break;
            case 2:
               createSingleStudent();
               break;
            case 3:
               // SC11: Code that exits the program
               break loop;
            default:
               // SC5 Code for range violation
               System.out.println("Your entry is out of range.");
         }
      }
      System.out.println("Goodbye!");
   }

   private static void createSingleStudent() {
      System.out.println("You are now creating a single student");
      // Option 2, Step 2
      System.out.println("Enter in the first name");
      String firstName = scanner.nextLine();
      // Option 2, Step 3
      System.out.println("Enter in the last name");
      String lastName = scanner.nextLine();
      // Option 2, Step 4
      int gradeLevel = option2Step4();
      // Option 2, Step 5
      double gpa = option2Step5();
      students.add(new Students(firstName, lastName, gradeLevel, gpa));
      printStudents();
   }
    
   private static double option2Step5() {
      double gpa = 0;
      while(true) {
         System.out.println("Enter in the GPA in its proper format (#.##)");
         // SC8: Code try-catch for invalid data
         try {
            gpa = scanner.nextDouble();
         } catch(InputMismatchException e) {
            System.out.println("ERROR: Please enter valid data type");
            continue;
         } finally {
            scanner.nextLine();
         }
         // SC8: Code range violation
         if(gpa < 0 || gpa > 4) {
            System.out.println("Your entry is out of range.");
            continue;
         }
         break;
      }
      return gpa;
   }
    
   private static int option2Step4() {
      int gradeLevel = 0;
      while(true) {
         System.out.println("Enter in the student grade level");
         // SC7: Code try-catch for invalid data
         try {
            gradeLevel = scanner.nextInt();
         } catch(InputMismatchException e) {
            System.out.println("ERROR: Please enter valid data type");
            continue;
         } finally {
            scanner.nextLine();
         }
         // SC7: Code for range violation
         if(gradeLevel < 9 || gradeLevel > 12) {
            System.out.println("Your entry is out of range.");
            continue;
         }
         break;
      }
      return gradeLevel;
   }

   	
private static int option1Step2() {
   int val = 0;
   loop: while(true) {
      System.out.print("\nPlease enter in a value between 1 and 50: ");
      // SC6 Code with try/catch exception for invalid data error
      try {
         val = scanner.nextInt();
      } catch(InputMismatchException e) {
         System.out.println("ERROR: Please enter valid data type");
         continue;
      } finally {
         scanner.nextLine();
      }
      // SC6 Code for range violation
      if(val < 1 || val > 50) {
         System.out.println("Your entry is out of range.");
         continue;
      }
      break;
   }
   return val;
}




}


// SC1: All constructors, methods, and variables are appropriately created.
class Students {
   // Create appropriately variables based upon constructor parameters
   private String firstName;
   private String lastName;
   private int gradeLevel;
   private double gpa;

   // Generic Constructor
   public Students() {

   }

   // Constructor with Parameters
   public Students(String firstName, String lastName, int gradeLevel, double gpa) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.gradeLevel = gradeLevel;
      this.gpa = gpa;
   }

   // SC10: Returns "last name, first name" with required convention
   public String getWholeName() {
      return String.format("%s%s, %s%s", 
      lastName.substring(0, 1).toUpperCase(), 
      lastName.substring(1).toLowerCase(),  
      firstName.substring(0, 1).toUpperCase(),
      firstName.substring(1).toLowerCase());
   }



   // Returns first name
   public String getFirstName() {
      return firstName;
   }

   // Returns last name
   public String getLastName() {
      return lastName;
   }

   // Returns the GPA
   public double getGPA() {
      return gpa;
   }

   // SC9: Returns the GPA formatted with proper DecimalFormat object
   public String getGPAStr() {
      DecimalFormat df = new DecimalFormat("#.00");
      return df.format(gpa);
   }

   // Returns grade level
   public int getGradeLevel() {
      return gradeLevel;
   }



}

What is CSV?

  • CSV (comma-separated values) files are a standard data text storage format.

  • They are easy to edit in any text editor or spreadsheet software.

  • Download this CSV file and save it in the root directory of your project folder.

  • The first line is an optional heading row. It contains attribute names.

  • Each field (column) is separated by a comma, called a delimiter.

  • The delimiter can also be a tab  (TSV) any other character.

  • All other lines are individual data records.

  • Records should represent one type of entity.

  • Click the Download button at the bottom of this page to see a more complex example.

President Class

  • Using the first line header row, create a President class with 6 attributes 

import java.time.LocalDate;

public class President {
    private int id;
    private String firstName;
    private String lastName;
    private int heightInInches;
    private double weightInPounds;
    private LocalDate dateOfBirth;

    public President() {}

    public President(int id, String firstName, String lastName, int heightInInches, double weightInPounds,
            LocalDate dateOfBirth) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.heightInInches = heightInInches;
        this.weightInPounds = weightInPounds;
        this.dateOfBirth = dateOfBirth;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getHeightInInches() {
        return heightInInches;
    }

    public void setHeightInInches(int heightInInches) {
        this.heightInInches = heightInInches;
    }

    public double getWeightInPounds() {
        return weightInPounds;
    }

    public void setWeightInPounds(double weightInPounds) {
        this.weightInPounds = weightInPounds;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    @Override
    public String toString() {
        return "President [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", heightInInches="
                + heightInInches + ", weightInPounds=" + weightInPounds + ", dateOfBirth=" + dateOfBirth + "]";
    }
    
}

FileInput Class

  • Create a class to read all lines or a single line from a file.

  • Per this page, don't use Scanner object if you want to read the file line by line

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class FileInput {
    private static String pathToFiles = "src/";

    public static List<String> readAllLines(String filename) {
        List<String> lines = null;
        try {
            lines = Files.readAllLines(Paths.get(pathToFiles + filename));
        } 
        // try(Scanner scanner = new Scanner(new File(pathToFiles + filename))) {
        //     lines = new ArrayList<>();
        //     while(scanner.hasNextLine()) {
        //         lines.add(scanner.nextLine());
        //     }
        // } 
        catch (IOException e) {
            System.out.println("The " + filename + " file doesn't exist.");
            System.exit(0);
        }
        return lines;
    }

    public static String readFirstLine(String filename) {
        String line = "";
        try(Scanner scanner = new Scanner(new File(pathToFiles + filename))) {
            line = scanner.nextLine();
        } catch (FileNotFoundException e) {
            System.out.println("Error reading file " + filename + ".");
            System.exit(0);
        } catch (NoSuchElementException e) {
            System.out.println("Cannot read line from " + filename + ".");
            System.exit(0);
        }
        return line;
    }

    public static void main(String[] args) {
        List<String> lines = readAllLines("presidents.csv");
        lines.forEach(System.out::println);
        String line = readFirstLine("presidents.csv");
        System.out.println(line);
    }

}

PresidentDAO Class

  • Create a class that is used to convert lines from the text file to objects.

  • Create a method to read data from a data file.

import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;


public class PresidentDAO {
    private static List<President> presidents = new ArrayList<>();
    
    public static void main(String[] args) {
        getPresidents().forEach(System.out::println);
    }

    public static List<President> getPresidents() {
        if(presidents.size() == 0) {
             getFromCSV();
        }
        return presidents;
    }

    private static void getFromCSV() {
        List<String> lines = FileInput.readAllLines("presidents.csv");
        for(String line: lines) {
            String[] president = line.split(",");
            try {
                int id = Integer.parseInt(president[0].trim());
                String firstName = president[1].trim();
                String lastName = president[2].trim();
                int height = Integer.parseInt(president[3].trim());
                double weight = Double.parseDouble(president[4].trim());
                LocalDate dateOfBirth = LocalDate.parse(president[5].trim());
                presidents.add(new President(id, firstName, lastName, height, weight, dateOfBirth));
            } catch(IndexOutOfBoundsException | NumberFormatException | DateTimeParseException e) {
                // Skip the line if it is missing a field, or if the String cannot be converted into an int, double, or LocalDate.
                continue;
            }
        }
    }
    
}

CSV Libraries

  • https://www.baeldung.com/apache-commons-csv

  • https://github.com/super-csv/super-csv

  • https://super-csv.github.io/super-csv/index.html

  • https://github.com/42BV/CSVeed

  • https://42bv.github.io/CSVeed/csveed.html

  • https://opencsv.sourceforge.net/

  • https://www.baeldung.com/opencsv

  • https://jenkov.com/tutorials/java-io/bufferedoutputstream.html

Java 2 - Week 2

By Marc Hauschildt

Java 2 - Week 2

  • 227