Advanced Java Concept Unit 1. Mostly Review Program 1. Create a class that has only a main method. In the main method create an ArrayList of Integers (remember the import statement). Add 10 random integers to the ArrayList. These should have values between 1 and 10. Here s the formula for generating random integers (pat yourself on the back if you still remembered it). (int)( range * Math.random() ) + min where range = max - min + 1 Print out the 10 random integers on one line. Then write a loop which deletes all the odd numbers. Print out the contents of the array list. Try to use an enhanced for-loop when printing out the values. Run it more than once and check that sequential odd values are correctly deleted. Program 2. Copy the RememberStrings file and complete the countwhitespace and countword methods. Program 3. Copy the RunCommas file and complete the addcommas method. Program 4. Copy and complete the Average class. Copy and run the RunAverage class to check your solution. A sensor (e.g. a sonic sensor that detects distance to a target) might return mostly good data with an occasional bad value due to some random occurrence. One solution to this problem is to smooth the data by averaging the last n values. The average class is designed to solve the above problem. Data can be added to an average object and it will return the average of the last n values. If there are less than n values, it calculates the average of whatever it has. In the RunAverage class, there are three test cases. In the first test case, an average object is calculating the average of the last two values. - the first value is 6 and the average is 6 - the second value is 9 and the average of the two is 15/2 = 7.5 - the third value is 6 and average of the last two is (6+9)/2 = 7.5 and so on. In the second test case, the last three values are averaged. In the third test case, the last eight values are averaged. 1
Throwing and Catching Exceptions. Consider the code below. 1 public class Exceptions1{ 2 public static void main( String[] args ){ 3 try { 4 int n = 10 / 0; 5 catch (ArithmeticException ex){ 6 System.out.println( "Don't divide an int by 0" ); 7 finally{ 8 System.out.println( "This section is optional but sometimes useful" ); 9 10 11 In the above example, the program did NOT crash at line 4. The run-time error was caught line 6 was executed. Note. The curly braces associated with the try, catch, and finally sections are always required. The above example just demonstrates the concept but is otherwise useless. Here s a better example. import java.util.scanner; import java.util.inputmismatchexception; public class Exceptions2{ public static void main( String[] args ){ Scanner scan = new Scanner( System.in ); System.out.println( "Enter an integer" ); boolean success = true; int n; try { n = scan.nextint(); catch ( InputMismatchException ex ){ success = false; n = 0; if ( success ) System.out.println( "You entered " + n ); else System.out.println( "Not an integer so a default value of zero will be used" ); In this example we can use a try-catch to handle possible input problems. There are two approaches to determining what exception might be generated. (1) Go the API and look up the nextint method in the Scanner class. (2) Run the code without a try-catch and deliberately enter bad data and see what exceptions occur. Note. There can be more than one catch section if you need to catch multiple exceptions. 2
Program 5. Copy and complete the String2Integer class. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ There are two types of exceptions. unchecked exceptions. These exceptions do not have to be handled by the client code. This is what the previous examples and problem are concerned with. checked exceptions. These exceptions must be handled by the client code by using try-catch (or by using the throws clause which we won t talk about). When reading files, there are almost always (always?) checked exceptions that must be dealt with. Consider the following code. import java.util.scanner; import java.io.file; import java.io.filenotfoundexception; public class FileExample{ public static void main( String [] args ){ File f = new File( "text.txt" ); try { Scanner in = new Scanner( f ); int n = 0; while( in.hasnext() ){ String str = in.nextline(); System.out.println( "Line " + n + ": " + str ); n++; catch (FileNotFoundException ex ) { System.out.println( "File not found." ); The try-catch is required here. If it were deleted, the compiler error would be: unreported exception java.io.filenotfoundexception; must be caught or declared to be thrown Program 6. Copy and complete the ReadFile program. The program should print all lines that are not integers. If a line consists of a single integer, add that to a total and print the total at the end of the program. On the left is a simple text file and on the right is what the program should display. You should use the isinteger method that you wrote for program 5. 3
The split method is a very useful method of the String class that will split a string into an array of strings based on the value(s) you give it. Here is a simple example. import java.util.arrays; The Arrays class has a public class splitstringexample{ public static void main( String [] args ){ number of useful methods for working with arrays. String commas = "2,cat,3,8"; String [] a1 = commas.split( "," ); String s = Arrays.toString( a1 ); System.out.println( s ); // [2, cat, 3, 8] String semis = "this is;another example;;!"; String [] a2 = semis.split( ";" ); System.out.println( a2.length ); // 4 System.out.println( a2[0] ); // this is Program 7. A CSV (comma separated values) file is a simple spreadsheet with each column separated by a comma (or semicolon). Each row is a separate line. I found a csv file on cereals at https://perso.telecom-paristech.fr/~eagan/class/igr204/datasets If you look at the URL, it s from a French school though this page is in English. I don t know if the information is accurate but that s not really that important to this exercise. The file, cereal.csv, uses semi-colons to delimit (separate) the data. The first row contains column headers. There are 16 columns. They are: name, manufacturer, type, calories, fat, sodium, fiber, carbohydrates, sugars, potassium, vitamins, shelf (not sure what that means), weight, cups, and rating. Who generated this data? What are the units for these fields? So many good questions but let s ignore them and just read the data. The second row shows the data types for each column. Create a Cereal class that has three private instance variables: name, calories, and rating. We will ignore all the other information in the file. Add three accessor methods. Your program should read the file and create an ArrayList of cereal objects. Then print the following: The number of cereals The cereal with the longest name The average calorie count (as a double) for all the cereals The cereal with the highest calorie count (print the name and calories) The cereal with the smallest calorie count (print the name and calories) The cereal with the highest rating The cereal with the lowest rating In case of a tie, show any of the correct possible answers. You may assume the file is correctly formatted and has at least 3 lines. 4
Program 8. The titanic.csv file contains information about the numbers of people who survived and died by class, sex, and age. I got the file from https://vincentarelbundock.github.io/rdatasets/datasets.html and after about 5 minutes of exhaustive research I am comfortable that these numbers are reasonable. Write a program that reads the file and answers the following questions. What is the likelihood of surviving if you were in 1 st class vs 2 nd class vs 3 rd class vs crew? What is the likelihood of surviving if you were male? Female? What is the likelihood of surviving if you were a child? An adult? Of the 16 different combinations (e.g. Adult male in 1 st class or Female child in 3 rd class), which is the one that was most likely not to survive? Note. Some combinations did not occur (e.g. there were no children in the crew) so do not consider those. When writing the program, try to be as efficient as possible. 5