CS 112 Introduction to Programming
|
|
- Ashlyn Brown
- 6 years ago
- Views:
Transcription
1 CS 112 Introduction to Programming File as Input; Exceptions; while loops; Basic Arrays Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
2 Admin. q PS4 status q Kevin s Crash Review on Tuesday from 7 to 8 pm at AKW 400 q Puzzle Day from Friday to Monday 2
3 Recap q switch statement q String processing Access methods, e.g., length, substring, charat, indexof New string generator methods, e.g. tolowercase, touppercase, replace Output formatting: format string System.out.printf, String.format Boolean methods, e.g., equals, equalsignorecase, startswith, endswith, contains,
4 String charat method q The chars in a String can be accessed using the charat method. String food = "cookie"; char firstletter = food.charat(0); // 'c' System.out.println(firstLetter + " is for " + food); System.out.println("That's good enough for me!"); q You can use a for loop to print or examine each character. String major = "CS"; for (int i = 0; i < major.length(); i++) { char c = major.charat(i); System.out.println(c); } Output: C S
5 char vs. String q "h" is a String 'h' is a char (the two behave differently) q String is an object; it contains methods String s = "h"; s = s.touppercase(); // 'H' int len = s.length(); // 1 char first = s.charat(0); // 'H' q char is primitive; you can't call methods on it char c = 'h'; c = c.touppercase(); // ERROR
6 char vs. String: Comparison q You can compare char values with relational operators (ordering is alphabetical order): 'a' < 'b' and 'X' == 'X' and 'Q'!= 'q String word = console.next(); if (word.charat(word.length() - 1) == 's') { System.out.println(word + " is plural."); }
7 char vs. String: Comparison q Relational operators such as!= and == compares objects by references (seen later), so it often gives false even when two Strings have the same letters. Scanner console = new Scanner( System.in ); String name = console.next(); // user input Barney if (name == "Barney") { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!"); }
8 char vs. int q Using char in arithmetic expressions will cause char to be converted to an int q To convert an int into the equivalent char, type-cast it. (char) ('a' + 2) is 'c' for (char c = 'a'; c <= 'z'; c = (char)(c+1) ) { System.out.print(c); } for (char c = 'a'; c <= 'z'; c ++ ) { System.out.print(c); }
9 Caesar Cipher If he had anything confidential to say, he wrote it in cipher, that is, by so changing the order of the letters of the alphabet, that not a word could be made out. If anyone wishes to decipher these, and get at their meaning, he must substitute the fourth letter of the alphabet, namely D, for A, and so with the others. Suetonius, Life of Julius Caesar 56
10 Caesar Cipher Plaintext attack said zeus προσβάλλω Ciphertext dwwdfn vdlg chxv στςφείξξό
11 Why Programming? 11
12 Caesar Cipher: Encoding Letter a b c d... w x y z Orig Shift (+3) Cipher (% 26) int cipherint = (origint + key) % 26
13 Caesar Cipher: Decoding Letter a b c d... w x y z Cipher Shift (-3) Text (+26 % 26) int origint = (cipherint key + 26) % 26
14 Unifying Design int cipherint = (origint + key) % 26 int origint = (cipherint key + 26) % 26 q A single encode method with parameter key To encode encode(key) To decode encode(26 key)
15 Extension: Encrypt a Text File q Goal: Instead of reading text from terminal, user specifies a file name, which gives the content to be encrypted. 15
16 Reading Specific Files in Program q To read a file, pass a File when constructing a Scanner. Example: File file = new File("mydata.txt"); Scanner input = new Scanner(file); or (shorter): Scanner input = new Scanner(new File("mydata.txt"));
17 Prompting and Checking Files q Recall: we can ask the user to tell us the file to read. // prompt for input file name Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextline(); // next()? Scanner input = new Scanner(new File(filename)); q You can use File s exists method to test existence: File file = new File( data.txt"); if (!file.exists() ) { // try a second input file as a backup System.out.print( data file not found!"); file = new File( data2.txt"); }
18 Compiler Error w/ Scanning File import java.io.*; import java.util.*; // for File // for Scanner public class ReadFile { public static void main(string[] args) { File f = new File( msg.txt") Scanner input = new Scanner( f ); String text = input.next(); System.out.println(text); } } q The program fails to compile with the following error: ReadFile.java:9: unreported exception java.io.filenotfoundexception; must be caught or declared to be thrown Scanner input = new Scanner( f ); ^
19 Exceptions q Exception: representing a runtime error, e.g., dividing an integer by 0 calling substring on a String and passing too large an index trying to read the wrong type of value from a Scanner trying to read a file that does not exist q Java allows a method to "throw" an exception, when the method detects a run-time error q Consequence: if a method A invokes a method B that may throw an exception, method A must declare how it handles the exception
20 Handle Checked Exception q Declare a throw clause q Use try/catch 20
21 The throws Clause q throws clause: Keywords on a method's header to state that it may generate an exception (and will not handle it). q Syntax: public static <type> <name>(...) throws <type> { Example: public class ReadFile { public static void main(string[] args) throws FileNotFoundException { Like saying, "I hereby announce that this method might throw an exception, and I accept the consequences if this happens."
22 The try/catch Structure q try/catch: if an exception happens, program execution jumps to the catch statement, skipping the rest in the try block. import java.io.*; import java.util.*; // for File // for Scanner public class ReadFile { public static void main(string[] args) { try { Scanner input = new Scanner(new File( msg.txt")); String text = input.next(); System.out.println(text); } catch (FileNotFoundException e) { // print an error message System.out.println( File not found exception ); } // end of catch } } // end of main 22
23 Remaining Issue q CaesarFile needs to read a file containing an arbitrary number of lines of text. Hence, it will need an indefinite loop. q Indefinite loops are common in programming design, e.g., Read from user until input is a non-negative number. Repeat until the user has typed "q" to quit. Print random numbers until a prime number is printed. Search for a solution in a set. q A key to define an indefinite loop is to identify the loop s test condition.
24 Scanner Test for Input Status Method hasnext() hasnextint() hasnextdouble() hasnextline() Description returns true if there is a next token returns true if there is a next token and it can be read as an int returns true if there is a next token and it can be read as a double returns true if there is a next line. q These methods of the Scanner do not consume input; they just give information about what the next input will be. 24
25 CaesarFile using for Loop public static void encode(scanner scan, int key) { for ( ; scan.hasnextline(); ) String text = scan.nextline(); reads ugly } } String result = Caesar.encode(text, key); System.out.println( result ); 25
26 Java Repetition /Loop Statements q Java has three kinds of loop statements: the for loop the while loop, the do loop, and q They have the same expressive power q Which loop statements to use will depend on the context to be more intuitive 26
27 The while loop q while loop: Repeatedly executes its body as long as a logical test is true. while (<test>) { <statement(s)>; } q Example: while is a keyword int num = 1; while (num <= 10) { System.out.print(num + " "); num = num * 2; } // output: // initialization // test // update
28 The do/while loop q do/while loop: Similar to while, except move test at the end: do { <statement(s)>; } while (<test>); q Example: int num = 1; // initialization do { System.out.print(num + " "); num = num * 2; // update } while (num <= 10); // test // output:
29 CaesarFile using a while Loop public static void encode(scanner scan, int key) { while ( scan.hasnextline() ) { String text = scan.nextline(); } } String result = Caesar.encode(text, key); System.out.println( result ); 29
30 Additional Usage of Caesar Cipher q Augustus Right shift 1 without rotate, with AA for Z q Mezuzah Shift of one to encrypt the names of God q Vigenere (a variant) was used by the Confederacy during Civil War q Mafia boss Provenzano (2006): A (4), 30
31 Exercise: Breaking Caesar Encryption q Caesar encryption (or permutation ciphers in general) is easy to break because it does not change the frequency of letters.
32 Frequency Analysis Code (Attempt 1) int na = 0, nb = 0, nc = 0, nd = 0, ne = 0, nf = 0, ng = 0, nz = 0; while ( scan.hasnextline() ) { String line = scan.nextline(); for (int i = 0; i < line.length(); i++) { char ch = line.charat( i ); if ( ch == a ) na ++; else if ( ch == b ) nb ++; else if ( ch == c ) nc ++; } // find the max of na, nb, nc, 32
33 Improving Attempt 1 q We need a way to declare many variables in one step. q We need an effective scheme to refer to the variables q The objective of array is to provide these
34 Arrays q array: object that stores many values of the same type. element: one value in an array. index: array element referred to by position number starting from 0 index value element 0 element 4 element 9
35 Array Declaration After declaration, all elements of an int array are initialized to 0. <type>[] <name> = new <type>[<length>]; Example: int[] numbers = new int[10]; index value o The length in declaration can be any non-negative integer expression, e.g., int x = 2 * 3 + 1; double[] data = new double[x + 2]; // arr w/ 9 elem
36 Accessing Array Elements <name>[<index>] // access <name>[<index>] = <value>; // modify numbers[ 0 ] 85 numbers[ 1 ] 60 int[] numbers = new int[10]; numbers[ 2 ] numbers[ 3 ] numbers[ 4 ] 54 position number (index or subscript) of the element within array numbers numbers numbers[ 5 ] numbers[ 6 ] numbers[ 7 ] numbers[ 8] numbers[ 9 ] 81 36
37 Accessing Elements: Example int[] numbers = new int[10]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; System.out.println(numbers[2-1]); if (numbers[4] > 10) { System.out.println( numbers[4] > 10."); } numbers index value BasicArrays.java
38 Accessing Elements: Example q What does this code segment do? int[] numbers = new int[8]; numbers[0] = 1; numbers[1] = 1; for (int i = 2; i < 8; i++) { numbers[i] = numbers[i-1] + numbers[i-2]; } index value
39 Backup Slides 39
40 File Input/output (I/O) import java.io.*; q Create a File object to get info about a file on your drive. (This doesn't actually create a new file on the hard disk.) File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); } Method name canread() delete() exists() getname() length() Description returns whether file is able to be read removes file from disk whether this file exists on disk returns file's name returns number of bytes in file
41 File Paths q Absolute path: specifies a drive or a top "/" folder C:/Documents/smith/prob6/input/data.csv Windows can also use backslashes to separate folders. q Relative path: does not specify any top-level folder names.dat input/kinglear.txt Assumed to be relative to the current directory: Scanner input = new Scanner(new File("data/readme.txt")); If our program is in C:/prob6, File will look for C:/prob6/data/readme.txt ReadFile.java
Building Java Programs
Building Java Programs Chapter 6 File Input with Scanner reading: 6.1 6.2, 5.4 2 Input/output (I/O) import java.io.*; Create a File object to get info about a file on your drive. (This doesn't actually
More informationAP Computer Science. File Input with Scanner. Copyright 2010 by Pearson Education
AP Computer Science File Input with Scanner Input/output (I/O) import java.io.*; Create a File object to get info about a file on your drive. (This doesn't actually create a new file on the hard disk.)
More informationBuilding Java Programs
Building Java Programs Chapter 6: File Processing Lecture 6-1: File input using Scanner reading: 6.1-6.2, 5.3 self-check: Ch. 6 #1-6 exercises: Ch. 6 #5-7 Input/output ("I/O") import java.io.*; Create
More informationBuilding Java Programs
Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, 4.3-4.4 self-check: Ch. 4 #12, 15 exercises: Ch. 4 #15, 16 videos: Ch. 3 #3 1 Objects and classes object: An entity that contains: data
More informationFile class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". Input is received from the keyboard, mouse, files.
More informationBuilding Java Programs
Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1-6.2, 5.3 self-check: Ch. 6 #1-6 exercises: Ch. 6 #5-7 videos: Ch. 6 #1-2 Input/output (I/O) import java.io.*; Create a
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationTopic 23 arrays - part 3 (tallying, text processing)
Topic 23 arrays - part 3 (tallying, text processing) "42 million of anything is a lot." -Doug Burger (commenting on the number of transistors in the Pentium IV processor) Copyright Pearson Education, 2010
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignment Class Exercise 19 is assigned Homework 8 is assigned Both Homework 8 and Exercise 19 are
More informationBuilding Java Programs Chapter 4
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson 2013. All rights reserved. The if statement Executes a block of statements only if a test is true if (test) { statement;...
More informationAdmin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements
Admin. CS 112 Introduction to Programming q Puzzle Day from Friday to Monday Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin. q Puzzle Day
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Program Analysis Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin q PS5 Walkthrough Thursday
More informationBuilding Java Programs Chapter 6
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson 2013. All rights reserved. Input/output (I/O) import java.io.*; Create a File object to get info about a file on your drive. (This
More informationBuilding Java Programs
Building Java Programs Chapter 6: File Processing 1 file input using Scanner Chapter outline File objects exceptions file names and folder paths token-based file processing line-based file processing processing
More informationBuilding Java Programs
Building Java Programs Chapter 4 Lecture 4-3: Strings; char; printf; procedural design reading: 3.3, 4.3, 4.5 1 Strings reading: 3.3 1 Strings string: An object storing a sequence of text characters. Unlike
More informationCIS 110: Introduction to Computer Programming
CIS 110: Introduction to Computer Programming Lecture 15 Our Scanner eats files ( 6.1-6.2) 10/31/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Programming assertion recap The Scanner object
More informationBuilding Java Programs
Building Java Programs Chapter 7: Arrays Lecture 7-3: More text processing, file output 1 Remember: charat method Strings are internally represented as char arrays String traversals are a common form of
More informationFile Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File
Unit 4, Part 2 File Processing Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File The File class in Java is used to represent a file on disk. To use it,
More informationCS 112 Introduction to Programming
Sierpinski Valentine http://xkcd.com/543/ 1 CS 112 Introduction to Programming Switch; Text Processing Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:
More informationSierpinski Valentine.
Sierpinski Valentine http://xkcd.com/543/ 1 CS 112 Introduction to Programming Switch; Text Processing Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin
More informationBuilding Java Programs
Building Java Programs Chapter 6: File Processing Lecture 6-2: Advanced file input reading: 6.3-6.5 self-check: #7-11 exercises: #1-4, 8-11 Copyright 2009 by Pearson Education Hours question Given a file
More informationExcep&ons and file I/O
Excep&ons and file I/O Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Variables; Type Casting; Using Variables in for Loops Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
More informationBuilding Java Programs
Building Java Programs Chapter 4 Lecture 4-3: Strings; char reading: 3.3, 4.3 1 Strings reading: 3.3 Objects object: An entity that contains data and behavior. data: variables inside the object behavior:
More informationCSCI 1103: File I/O, Scanner, PrintWriter
CSCI 1103: File I/O, Scanner, PrintWriter Chris Kauffman Last Updated: Wed Nov 29 13:22:24 CST 2017 1 Logistics Reading from Eck Ch 2.1 on Input, File I/O Ch 11.1-2 on File I/O Goals Scanner for input
More informationBuilding Java Programs
Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1-6.2, 5.3 self-check: Ch. 6 #1-6 exercises: Ch. 6 #5-7 videos: Ch. 6 #1-2 Input/output (I/O) import java.io.*; Create a
More informationClasses Basic Overview
Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container
More informationBuilding Java Programs
Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 Loops with if/else if/else statements can be used with
More informationText processing. Readings: 4.4
Text processing Readings: 4.4 1 Characters char: A primitive type representing single characters. Individual characters inside a String are stored as char values. Literal char values are surrounded with
More informationReading Input from Text File
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014 The simplest
More information! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like
Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is
More informationFull file at
Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as
More informationSierpinski Valentine. q Our journey of introducing conditionals
Sierpinski Valentine http://xkcd.com/543/ CS 112 Introduction to Programming Switch; Text Processing Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:
More informationCSE 373. Data Types and Manipulation; Arrays. slides created by Marty Stepp
CSE 373 Data Types and Manipulation; Arrays slides created by Marty Stepp http://www.cs.washington.edu/373/ University of Washington, all rights reserved. 1 Numeric data type kind of number memory (bits)
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2 Copyright 2009
More informationText User Interfaces. Keyboard IO plus
Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: File Output; Reference Semantics reading: 6.4-6.5, 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5 Two separate topics File output A lot like printing
More informationCS244 Advanced Programming Applications
CS 244 Advanced Programming Applications Exception & Java I/O Lecture 5 1 Exceptions: Runtime Errors Information includes : class name line number exception class 2 The general form of an exceptionhandling
More informationAdmin. CS 112 Introduction to Programming. Recap: Arrays. Arrays class. Array Return (call) Array Return (declare) q Exam 1 Max: 50 Avg/median: 32
Admin 100# 95# 90# 85# 80# CS 112 Introduction to Programming q Exam 1 Max: 50 Avg/median: 32 75# 70# 65# 60# 55# 50# 45# 40# 35# 30# 25# Reference Semantics; 2D Arrays; Array as State Yang (Richard) Yang
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Reference Semantics; 2D Arrays; Array as State Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Reference Semantics; 2D Arrays; Array as State Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin
More informationCSCI 1103: File I/O, Scanner, PrintWriter
CSCI 1103: File I/O, Scanner, PrintWriter Chris Kauffman Last Updated: Mon Dec 4 10:03:11 CST 2017 1 Logistics Reading from Eck Ch 2.1 on Input, File I/O Ch 11.1-2 on File I/O Goals Scanner for input Input
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More informationCS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.
CS 112 Introduction to Programming CS112@Yale Loop Patterns: Fencepost Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu http://www.ultimateecards.com/image/772-jan-29-national-puzzle-day-card
More informationText processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char
Characters Text processing Readings: 4.4 (pg. 235 237) char: A primitive type representing single characters. Individual characters inside a String are stored as char values. Literal char values are surrounded
More informationObject Oriented Programming Exception Handling
Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationEXCEPTIONS. Fundamentals of Computer Science I
EXCEPTIONS Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)
More informationAP Computer Science A
AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void
More informationEXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {
EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could
More informationCOSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan
COSC 123 Computer Creativity I/O Streams and Exceptions Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Objectives Explain the purpose of exceptions. Examine the try-catch-finally
More informationBuilding Java Programs
Building Java Programs Chapter 6 Line-Based File Input reading: 6.3-6.5 2 Hours question Given a file hours.txt with the following contents: 123 Alex 12.5 8.2 7.6 4.0 456 Alina 4.2 11.6 6.3 2.5 12.0 789
More informationCSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige
CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors
More informationCSE 143 Lecture 22. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp
CSE 143 Lecture 22 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target
More informationCSE 143 Lecture 21. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp
CSE 143 Lecture 21 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target
More informationChapter 4: Conditionals and Loops
Chapter 4: Conditionals and Loops CS 121 Department of Computer Science College of Engineering Boise State University April 9, 2015 Chapter 4: Conditionals and Loops CS 121 1 / 69 Chapter 4 Topics Flow
More informationTopic 13 procedural design and Strings
Topic 13 procedural design and Strings Ugly programs are like ugly suspension bridges: they're much more liable to collapse than pretty ones, because the way humans (especially engineerhumans) perceive
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics
WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java
More informationLoops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 6 Loops
More informationComputational Expression
Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name
More informationCS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling
CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5 Section attendance question Write a program that reads
More informationBuilding Java Programs
Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks: Ch. 7 #19-23 exercises: Ch. 7 #5 Section attendance question Write a program that reads
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCIS October 16, 2018
CIS 1068 October 16, 2018 administrative stuff @@@ ADD ME @@@ Midterm Remember, the material is cumulative You ll see this stuff again Legal Identifiers c00lg33k is a legal identifier Legal Identifiers
More informationPlace your name tag here
CS 170 Exam 1 Section 001 Spring 2015 Name: Place your name tag here Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output
WIT COMP1000 File Input and Output I/O I/O stands for Input/Output So far, we've used a Scanner object based on System.in for all input (from the user's keyboard) and System.out for all output (to the
More informationJava Flow of Control
Java Flow of Control SEEM 3460 1 Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements
More informationConstants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous
CS256 Computer Science I Kevin Sahr, PhD Lecture 25: Miscellaneous 1 main Method Arguments recall the method header of the main method note the argument list public static void main (String [] args) we
More informationExpress Yourself. What is Eclipse?
CS 170 Java Programming 1 Eclipse and the for Loop A Professional Integrated Development Environment Introducing Iteration Express Yourself Use OpenOffice or Word to create a new document Save the file
More informationCOMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015
COMP-202: Foundations of Programming Lecture 7: Strings and Methods Jackie Cheung, Winter 2015 Announcements Quiz 2 due tonight at 11:59pm New grades policy: lowest quiz mark dropped Assignment 2 due in
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationCSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp
CSE 143 Lecture 25 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides adapted from Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target
More informationChapter 8: Strings and Things
Chapter 8: Strings and Things Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Word Of Fortune Program this will be cleared when it's working 1-2 Chapter Topics Chapter 8 discusses
More informationOutline. CIS 110: Introduction to Computer Programming. Exam announcements. Programming assertions revisited. An extended example: mystery
Outline CIS 110: Introduction to Computer Programming Programming assertion recap The object and files Token-based file processing Lecture 15 Our eats files ( 6.1-6.2) 1 2 Exam announcements Attempting
More informationCS 170 Java Programming 1. Week 10: Loops and Arrays
CS 170 Java Programming 1 Week 10: Loops and Arrays What s the Plan? Topic 1: A Little Review Use a counted loop to create graphical objects Write programs that use events and animation Topic 2: Advanced
More informationCMPT 125: Lecture 4 Conditionals and Loops
CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed
More informationInput-Output and Exception Handling
Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Reading and writing text files Exceptions The try block catch and finally
More information1. An operation in which an overall value is computed incrementally, often using a loop.
Practice Exam 2 Part I: Vocabulary (10 points) Write the terms defined by the statements below. 1. An operation in which an overall value is computed incrementally, often using a loop. 2. The < (less than)
More informationCS 112 Introduction to Programming
CS 112 Introduction to Programming (Spring 2012) Lecture #8: More on Conditional & Loop Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements:
More informationFlow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators
Flow of Control of Program Statements CS 112 Introduction to Programming (Spring 2012) q Java provides two types of program flow of control statements: decision statements, or conditional statements: decide
More informationCOMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed
1 1 COMP200 INPUT/OUTPUT OOP using Java, based on slides by Shayan Javed Input/Output (IO) 2 3 I/O So far we have looked at modeling classes 4 I/O So far we have looked at modeling classes Not much in
More informationWES-CS GROUP MEETING #9
WES-CS GROUP MEETING #9 Exercise 1: Practice Multiple-Choice Questions 1. What is output when the following code executes? String S1 = new String("hello"); String S2 = S1 +! ; S1 = S1 + S1; System.out.println(S1);
More informationSequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;
Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationPROGRAMMING FUNDAMENTALS
PROGRAMMING FUNDAMENTALS Q1. Name any two Object Oriented Programming languages? Q2. Why is java called a platform independent language? Q3. Elaborate the java Compilation process. Q4. Why do we write
More informationboolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while
CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your
More informationCOSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com
More informationOutline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors
Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A
More informationCOMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015 Announcements Assignment 2 posted and due on 30 th of May (23:30). Extra class tomorrow
More informationRecap: Assignment as an Operator CS 112 Introduction to Programming
Recap: Assignment as an Operator CS 112 Introduction to Programming q You can consider assignment as an operator, with a (Spring 2012) lower precedence than the arithmetic operators First the expression
More informationConditionals and Loops
Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional
More informationBuilding Java Programs. Inheritance and Polymorphism
Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many
More informationComputer Science is...
Computer Science is... Computational complexity theory Complexity theory is the study of how algorithms perform with an increase in input size. All problems (like is n a prime number? ) fit inside a hierarchy
More information