Remember the football CSV homework from Sunday? In that problem, we worked with football data to learn all about how to use String methods to process data stored in a CSV.
In Java, we can parse CSVs using our usual arsenal of String methods: split(), substring(), trim(), equals(), indexOf(), charAt(), etc. You may also find it useful to convert String data into other data types (example: Integer.parseInt to convert String to int).
CSV Parsing Example
doublecalculateTotal(String csv){
double total = 0.0;
String[] lines = csv.split("\n");
for (String line: lines) {
String[] parts = line.split(",");
int price = Integer.parseInt(parts[1].trim());
int qty = Integer.parseInt(parts[2].trim());
total += price * qty;
}
return total;
}
String orders = """
Hot Dogs , 1, 67
Sandwiches, 2, 321
Fried Rice, 4, 542
""";
System.out.println(calculateTotal(orders));
Practice with CSV Parsing (10 minutes)
The Avengers are having a competition to see who won the most number of fist fights in 2020. They are storing this data in a CSV. Write a function that will take in a String and return a String array with the winner's name and their score.
The Avengers who are participating have "yes" stored next to their name. Only consider the Avengers who are participating in the competition.
Be sure to handle the empty String case and the null case using assert statements.
You can use Integer.parseInt(String) to go from int to String.
You can use String.valueOf(int) to go from String to int.
Use trim() to remove empty spaces.
Return a String array with 2 elements: the name of the winner and the score.
You may assume that all the participants will have unique scores.
Practice with CSV Parsing Starter Code (10 minutes)
String[] findWinner(String fistFights) {
// your code goes here
}
// fistFights CSV has 3 columns: name, inCompetition, score
String fistFights = """
Natasha, yes, 50
Steve, no, 34
Tony, yes, 64
T'Challa, no, 45
Thor, no, 108 """;
System.out.println(findWinner(fistFights)[0]); // prints Tony
System.out.println(findWinner(fistFights)[1]); // prints 64
String nullString = null;
System.out.println(findWinner(nullString)); // should produce assertion error
String emptyString = "";
System.out.println(findWinner(emptyString)); // should produce assertion error
Java Objects
We use objects ALL THE TIME in programming. Java is an object oriented language because it is based on objects. Objects typically contain some data (fields) and code (methods). Objects are also instances of classes.
Classes define how groups of objects behave. Let's take a look at objects and classes.
classSuperhero{ // this is the Superhero class // here's the data or fields
String name;
String power;
int age;
}
//antMan is an object or an instance of a class
Superhero antMan = new Superhero(); // use new to create instances
antMan.name = "Ant Man"; // we can access fields using dot notation
antMan.power = "Change body size";
antMan.age = 34;
Practice with Java Objects (10 minutes)
Create a class called Movie. The movie class should have 3 variables stored inside of it:
title representing the title of the movie
studio representing the studio that made the movie
rating representing the rating of Rotten Tomato movie rating
Create a class called Holiday. The holiday class should have 3 field variables.
name representing the name of the holiday
day representing the day (if the holiday is New Years Day, it should store 1)
month representing the month of the year (if the holiday is New Years Day, it should store January)
Create an instance of both classes using the new keyword and assign each of the fields to some value of your choice.
Java Object Methods
Objects encapsulate state and behavior. The state comes from the data fields or class variables in the class. The behavior is defined in the instance methods. The special thing about instance methods is that they automatically have access to that instance's variables.
classSuperhero{
// here's the data or fields
String name;
int age;
voidprint(){ // note that we don't need to pass in age or name
System.out.println(name + "'s age is " + age);
}
}
Superhero antMan = new Superhero();
antMan.name = "Ant Man";
antMan.age = 34;
antMan.print(); // calling the print instance method
Practice with Java Object Methods (10 minutes)
Let's go back to our movie and classes from the previous problem and create some instance methods for them.
Movie Class
create an instance of the Movie class if you haven't already and use dot notation to set the title, rating, and studio variables
create a void setRating(int num) method that takes in a rating as an integer and sets the rating to that value; ensure that the rating is a positive integer between 0 and 100 using assert statements
create a String getStudio() method that returns the name of the studio
create a void print() method that will not return anything but it will print out a statements like this: Sound of Music was produced by studioXYZ and has a rating of 83 on Rotten Tomatoes
Practice with Java Object Methods (10 minutes)
Holiday Class
create an instance of the Holiday class if you haven't already and use dot notation to set the name, day, and month variables.
create a int getDay() and String getMonth() methods that will return the day and month when call and do nothing else
create a void incrementDay() method that will increment the day for the holiday by one
create an void setMonth() method that will set the month to be the String that is passed in as an argument
That's all, folks
You worked on another CSV problem, built an entire Java class, and learned how to use Java methods - all in one hour! Good job today :)
Good luck on the midterm today. You'll kill it.
Fill out the feedback form if you have the chance and have a great day!
Solution Section
Practice CSV Parsing Solution
String[] findWinner(String fistFights) {
assert fistFights != null;
assert fistFights != "";
int highestScore = 0;
String bestFighter = null;
String[] lines = fistFights.split("\n");
for (String line: lines) {
String[] parts = line.split(",");
String inCompetition = parts[1].trim();
if (inCompetition.equals("yes")) {
if (Integer.parseInt(parts[2].trim()) > highestScore) {
highestScore = Integer.parseInt(parts[2].trim());
bestFighter = parts[0].trim();
}
}
}
String[] winner = {bestFighter, String.valueOf(highestScore)};
return winner;
}
// fistFights CSV has 3 columns: name, inCompetition, score
String fistFights = """
Natasha, yes, 3
Steve, no, 34
Tony, yes, 64
T'Challa, no, 6
Thor, no, 108 """;
System.out.println(findWinner(fistFights)[0]);
System.out.println(findWinner(fistFights)[1]);
String nullString = null;
System.out.println(findWinner(nullString)); // should produce an assertion error
String emptyString = "";
System.out.println(findWinner(emptyString)); // should produce an assertion error
Practice with Java Objects Solution
classMovie{
String title;
String studio;
int rating;
}
Movie movieOne = new Movie();
movieOne.title = "Sound of Music";
movieOne.studio = "I'm not sure";
movieOne.rating = 83;
classHoliday{
String name;
int day;
String month;
}
Holiday holidayOne = new Holiday();
holidayOne.name = "New Years Day";
holidayOne.day = 1;
holidayOne.month = "January";
Practice Java Object Methods Solution
classMovie{
String title;
String studio;
int rating;
voidsetRating(int newRating){
assert newRating <= 100;
assert newRating >= 0;
rating = newRating;
}
String getStudio(){
return studio;
}
voidprint(){
System.out.println(title + " was produced by "
+ studio
+ " and has a rating of "
+ rating + " on Rotten Tomatoes");
}
}
Movie movieOne = new Movie();
movieOne.title = "Sound of Music";
movieOne.studio = "studioXYZ";
movieOne.rating = 83;
movieOne.print();
System.out.println(movieOne.getStudio());
movieOne.setRating(100);
System.out.println(movieOne.rating);