Advanced Java Concept Unit 1. Mostly Review

Similar documents
Introduction to Computer Science Unit 2. Notes

AP CS Unit 3: Control Structures Notes

Introduction to Computer Science Unit 2. Exercises

APCS Semester #1 Final Exam Practice Problems

Introduction to Computer Science Unit 2. Notes

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Algorithms and Conditionals

Programming II (CS300)

Reading Input from Text File

BBM 102 Introduction to Programming II Spring Exceptions

COMP 202 Java in one week

AP Computer Science Unit 1. Programs

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Program 12 - Spring 2018

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Programming II (CS300)

Example Program. public class ComputeArea {

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Mr. Monroe s Guide to Mastering Java Syntax

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exceptions Handeling

Pace University. Fundamental Concepts of CS121 1

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exceptions and Libraries

AP Computer Science Unit 1. Writing Programs Using BlueJ

Computer Science is...

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

BBM 102 Introduction to Programming II Spring 2017

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

CS Programming I: Exceptions

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

( &% class MyClass { }

Supplementary Test 1

Programming Practice (vs Principles)

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Typecasts and Dynamic Dispatch. Dynamic dispatch

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

AP Computer Science A

Comp 249 Programming Methodology Chapter 9 Exception Handling

Object Oriented Programming Exception Handling

CS111: PROGRAMMING LANGUAGE II

9. Java Errors and Exceptions

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

Building Java Programs

Lab and Assignment Activity

Building Java Programs

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Chapter 3. Selections

CSCI 1103: File I/O, Scanner, PrintWriter

ing execution. That way, new results can be computed each time the Class The Scanner

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Practice Midterm 1 Answer Key

Bjarne Stroustrup. creator of C++

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Introduction to Software Design

Full file at

ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists

Programming Assignment Comma Separated Values Reader Page 1

St. Edmund Preparatory High School Brooklyn, NY

Introduction to Computer Science II CS S-22 Exceptions

Files & Exception Handling. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Fundamentals of Programming Data Types & Methods

CS Programming I: Exceptions

Excep&ons and file I/O

CS1083 Week 2: Arrays, ArrayList

Exception-Handling Overview

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CIS 110: Introduction to Computer Programming

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Section 2.2 Your First Program in Java: Printing a Line of Text

Chapter 12 Exception Handling

Java I/O and Control Structures

Name: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.

Repetition CSC 121 Fall 2014 Howard Rosenthal

! This week: Chapter 6 all ( ) ! Formal parameter: in declaration of class. ! Actual parameter: passed in when method is called

CS 251 Intermediate Programming Java Basics

ASSIGNMENT 5 Objects, Files, and a Music Player

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

Objektorienterad programmering

CS159. Nathan Sprague

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Exceptions - Example. Exceptions - Example

Programming with Java

COMP 202 Java in one week

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP-202 Unit 9: Exceptions

Transcription:

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