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

Size: px
Start display at page:

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

Transcription

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

2 Notice Assignment Class Exercise 19 is assigned Homework 8 is assigned Both Homework 8 and Exercise 19 are due this Sunday 2

3 Review do/while Loop The while loop is not the only indefinite loop In a while loop the test expression is evaluated before entering the loop This means it is possible that the loop code is never executed But sometimes we know that we need... at least one pass through the loop For situations like this the do/while loop is a better choice In a do/while loop the test expression is evaluated... at the bottom of the loop... after the loop code has been executed at least once 3

4 do/while Loop It has the following syntax do { STATEMENT;... while (TEST_EXPRESSION) ; The loop body will always be executed at least once After that, the loop will continue... as long as the test expression is true 4

5 do/while Loop Let's rewrite the program that rolls dice... using a do/while loop import java.util.*; public class DoWhile { public static void main(string[ ] args) { Random ranfactory= new Random() ; int sum; do { // roll the dice once int die1 = ranfactory.nextint(6) + 1; int die2 = ranfactory.nextint(6) + 1; sum = die1 + die2; System.out.println(die1 + " + " + die2 + " = " + sum) ; while (sum!= 7) ; $ java DoWhile = = = = = 7 5

6 The boolean Data Type The boolean data type allows only two possible value true false Boolean expressions are expressions... whose value can only be true or false true and false are reserved words in Java They are boolean literals You can assign a value to it using a literal boolean test = true; You can assign a value to it using a complex expression boolean even = (number % 2 == 0); 6

7 Logical Operators In Java you can form boolean expressions using logical operators Operator Meaning Example Value && AND (conjunction) (2 == 2) && (3 < 4) TRUE OR (disjunction) (1 < 2) ( 2 == 3) TRUE! NOT (negation)! (2 == 2) FALSE The NOT operator,!... reverses the truth value of its operands So if the operand is true... the NOT operator makes it false... and vice versa 7

8 Logical Operators We can express this in a truth table for NOT,! Here is the truth table for AND, && and the truth table for OR, 8

9 Updated Order of Precedence Now that we have three new operators... we have to see how they fit into the order of precedence Description Operators unary operators! multiplicative operators * / % additive operators + - relational operators < > <= >= Dealing with logical operators, Java will evaluate NOT,!, then AND, &&... and finally OR, equality operators ==!= logical AND && logical OR assignment operators = += -= *= /= %= &&= = 9

10 Short-Circuited Evaluation Java inherits a feature of the C language called short-circuited evaluation Whenever a boolean expression use the AND, &&, or OR,, operators... Java will stop the evaluating the expression if the value of the first operand... determines the value of the expression as a whole For example, if we have the expression stop < s.length() && s.charat(stop)!= ' ' There is no need to evaluate the second operand s.charat(stop)!= ' if we know the first operand is false stop < s.length() 10

11 Short-Circuited Evaluation since both operands must be true for && to be true If the first operand is false... we know the whole expression is false... without having to go further Similarly, if we have the expression height > 5 width > 5 There is no need to look at the value of width... if we know height is greater than 5 Another term for this feature is lazy evaluation 11

12 Boolean Variables and Flags Sometimes, while processing data, you want to take note of a special condition When the special condition occurs, a flag is set This allows the programmer to separate the action that sets the flag... from the response to that action Flags are boolean variables that are initially set to false The value of a flag is set to true, when something special or unusual happens Flags are often used in loops They are often used in while loops to signal that the work is done and that the loop should stop 12

13 Boolean Variables and Flags This make this code slightly longer... but is also makes it more readable... because we can assign a name to the test condition If we were writing a dating program... we might assign names to certain conditions... to make how we make our decisions clearer boolean cute = (looks >= 9) ; boolean smart = (IQ > 125) ; boolean rich = (income > ) ; boolean good_catch = cute && smart && rich; Sometimes a boolean variable... is used to record an unusual condition Such variables are called flags 13

14 Boolean Variables and Flags Flags are boolean variables that are initially set to false The value of a flag is set to true when something special or unusual happens Flags are often used in loops They are often used in while loops to signal that the work is done and that the loop should stop For example, you ask the users to keep entering a positive number and stop when a negative number is entered. boolean isnegative = false; while (!isnegative){ System.out.print("Please enter a positive integer: ); int number = console.nextint(); if (number < 0) { isnegative = true; 14

15 New Materials Outline Scanner Lookahead Dealing with Bad Data Files and File Objects Using a File Object Reading a File with a Scanner Token-Based Processing 15

16 Scanner Lookahead A Scanner object has "next" methods that wait for input from the user... and when the user enters something and hits Enter.. reads the characters from the command line... and turns them into values of the right data type... which are returned to the calling method Here is a partial list of these methods Method Description next() nextdouble() nextint() nextboolean() reads the next token and returns it as a String reads the next token and returns it as a double value reads the next token and returns it as an int value reads the next token and returns it as an boolean value 16

17 Scanner Lookahead If we call one of these methods and the user enters something that can't be converted into the right data type an exception is thrown But well written code should check the input before reading in data To help you do this, a Scanner object has other methods... which can look at what the user has entered... and return true if the data entered... can be converted into a specific data type They do this without reading in the data 17

18 Scanner Lookahead For each "next" method there is a corresponding "has" method Method Description hasnext() hasnextdouble() hasnextint() reads the next token and returns true if it can be turned into a String value reads the next token and returns true if it can be turned into a double value reads the next token and returns true if it can be turned into a int value hasnextboolean() reads the next token and returns true if it can be turned into a boolean value Each of these "has" methods returns true if the value entered can be turned into the data type needed This allows us to look at an entry without trying to convert it into a data type That means we can avoid throwing an exception 18

19 Scanner Lookahead So if we are expecting an integer... we can call hasnextint before calling nextint... and keep prompting for the type of input we need until we get it When you call a hashnext method it waits.. until the user has hit the enter key Then it looks at the value entered... and returns true if the value can be converted into the proper type But the value has not actually been read in 19

20 New Materials Outline Scanner Lookahead Dealing with Bad Data Files and File Objects Using a File Object Reading a File with a Scanner Token-Based Processing 20

21 Dealing with Bad Data If you use one of the Scanner "has" methods and the user has entered text... which can be turned into the value you want... you call the appropriate "next" method to get the data... and convert it into the right data type But what if the data is of the wrong type? You asked for an integer and the user typed in "fifty seven? If the value is of the wrong type... you have to get rid of the text the user entered... in order to make way for a new entry 21

22 Dealing with Bad Data The text the user typed in is not used until you call one of the "next" methods If you don't "consume" this input, you will get an infinite loop If we run the following program and don t type in an integer, we will stuck in infinite loop import java.util.* ; public class ReadIntBad{ public static void main (String[] args){ Scanner input = new Scanner(System.in); System.out.print("Please enter an integer "); while (! input.hasnextint()){ System.out.print("Please enter an integer "); int number = input.nextint(); System.out.println("You entered " + number); $ java ReadIntBad Please enter an integer: asdf Please enter an integer: Please enter an integer: Please enter an integer: Please enter an integer: 22

23 Dealing with Bad Data Since we did not get rid of the text entered by the user... hasnextint() keeps reading the same value again and again... which never changes We need to read in the value entered by the user and throw it away We do this by calling the next() method next() reads in the entire line of text entered by the user next() does not convert what the user entered We call next() to "consume" the bad entry... to make way for another entry 23

24 Dealing with Bad Data This is how we do it import java.util.* ; public class ReadIntGood{ public static void main (String[] args){ Scanner input = new Scanner(System.in); System.out.println("Please enter an integer: "); while (! input.hasnextint()){ input.next(); // read in the entry but don't use it System.out.println("Please enter an integer: "); int number = input.nextint(); System.out.println("You entered " + number); $ java ReadIntGood Please enter an integer: asdfa Please enter an integer: sdfgdfgh Please enter an integer: 57 You entered 57 24

25 New Materials Outline Scanner Lookahead Dealing with Bad Data Files and File Objects Using a File Object Reading a File with a Scanner Token-Based Processing 25

26 Files and File Objects One of the most important computer concepts is that of a file A file stored in a computer has a name and a location To get the contents of a file in Java, you need to construct a File object File f = new File("red_sox.txt"); The argument to the File constuctor is a pathname The pathname uniquely identifies a file It consists of A path The name of the file The path is the location of a file specified by the list of the directories that you must go through to get to the file In this course we will only use files in the current directory The pathname for files in the current directory is simply the name of the file 26

27 New Materials Outline Scanner Lookahead Dealing with Bad Data Files and File Objects Using a File Object Reading a File with a Scanner Token-Based Processing 27

28 Using a File Object Once you have created the File object... you can call its methods to get some information about the file Like this import java.io.*; // for the File class public class FileInfo { public static void main(string[] args) { File f = new File("red_sox.txt"); System.out.println("exists returns " + f.exists()); System.out.println("canRead returns " + f.canread()); System.out.println("length returns " + f.length()); System.out.println("getAbsolutePath returns " + f.getabsolutepath()); $ java FileInfo exists returns true exists returns true canread returns true length returns 629 getabsolutepath returns /Users/jiayinwang/Documents/drjava/class19/ red_sox.txtexample_code_cs114/6_chapter_examples_cs114/red_sox.txt 28

29 Using a File Object Here we called the File constructor with just the name of the file This works only if the file is in the current directory The File class is part of the java.io package, so we must have import java.io.*; at the top of any code that uses this class. io" is short for "input/output" The syntax of the file constructor is : File f = new File("red_sox.txt"); we are not creating a new file Instead we are creating a new File object to get the data in an existing file 29

30 Using a File Object Here are some of the more useful methods of the File class Method canread() delete() exists() getabsolutepath() getname() isdirectory() isfile() length() renameto(newname) Description Returns true if the file exists and can be read Deletes the file Returns true if the file exists on the system Returns the full path showing where this file is located Returns the name of the file as a String, without any path attached Returns true if the "file" is a directory (folder) on the system Returns true if the file is a file (not a directory) on the system Returns the number of characters in this file Changes this file s name to that of the parameter given 30

31 New Materials Outline Scanner Lookahead Dealing with Bad Data Files and File Objects Using a File Object Reading a File with a Scanner Token-Based Processing 31

32 Reading a File with a Scanner object When we need to get input from the user, we create a Scanner object like this Scanner console = new Scanner(System.in); But we can also use a Scanner object to read in data from other sources A Scanner object can also be used to read data from a file To do this, we first need to create a File object which gives us access to the file Once we have done this we can then pass this File object.. to the Scanner constructor File f = new File("red_sox.txt"); Scanner input = new Scanner(f); 32

33 Reading a File with a Scanner object After doing this we never need f again, so we can shorten the code as follows Scanner input = new Scanner(new File("red_sox.txt")); But if we try to run this we get a surprise import java.util.*; // for Scanner class import java.io.*; // for File class public class FileReaderBad { public static void main(string[ ] args) { Scanner input = new Scanner(new File("red_sox.txt")); System.out.print("Just created Scanner object for file"); $ javac FileReaderBad.java FileReaderBad.java:7: unreported exception java.io.filenotfoundexception; must be caught or to be thrown Scanner input = new Scanner(new File("red_sox.txt")); ^ 1 error 33

34 Reading a File with a Scanner object You would think that a FileNotFoundException would be something you would only see at runtime But a FileNotFoundException is a different kind of exception It is a checked exception that Java demands special treatment for them When your code could create one of these exceptions... Java insists that your code catch this exception... or, the method header must declare... that it might throw the exception 34

35 Reading a File with a Scanner object You do this by including a throws clause in the method header This will allow the compiler... to check every method that calls this particular method... to make sure it either catches the exception... or has the same throws clause in it's method header A throws clause looks like this public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("hamlet.txt"));... 35

36 Reading a File with a Scanner object Here is an example $ cat CountWords.java // Counts the number of words in a file. import java.io.*; import java.util.*; public class CountWords { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("red_sox.txt")); int count = 0; while (input.hasnext()) { String word = input.next(); count++; System.out.println("Total words = " + count); $ java CountWords Total words =

37 New Materials Outline Scanner Lookahead Dealing with Bad Data Files and File Objects Using a File Object Reading a File with a Scanner Token-Based Processing 37

38 Token-Based Processing When programmers talk about reading input from a text file... they talk about tokens A token is a string of character in the input... set off by special characters Usually tokens are set off from each other by whitespace The whitespace characters are Space Tab Newline Reading the content of a file token by token... is called token-based processing 38

39 Token-Based Processing If we have a file that contains the following The file contains 8 tokens... each of the tokens consists of decimal number... so we can use hasnextdouble() to see whether there is more input to process... and nextdouble() to read in the value of the token as a double 39

40 Token-Based Processing // Reads an input file of numbers and prints the numbers and // their sum. import java.io.*; import java.util.*; public class ShowSum { public static void main(string[ ] args) throws FileNotFoundException { Scanner input = new Scanner(new File("numbers.txt")); double sum = 0.0; int count = 0; while (input.hasnextdouble()) { double next = input.nextdouble(); count++; System.out.println("number " + count + " = " + next); sum += next; System.out.println("Sum = " + sum); $ java ShowSum number 1 = number 2 = 14.9 number 3 = 7.4 number 4 = 2.8 number 5 = 3.9 number 6 = 4.7 number 7 = number 8 = 2.8 Sum =

Building Java Programs

Building 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 information

AP Computer Science. File Input with Scanner. Copyright 2010 by Pearson Education

AP 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 information

Building Java Programs

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 information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 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 information

Reading Input from Text File

Reading 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

CIS 110: Introduction to Computer Programming

CIS 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 information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 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 information

Building Java Programs

Building 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 information

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

File 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 information

Excep&ons and file I/O

Excep&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 information

CS 112 Introduction to Programming

CS 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 information

Building Java Programs

Building 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 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

! 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 information

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 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 information

EXCEPTIONS. Fundamentals of Computer Science I

EXCEPTIONS. 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 information

Outline. CIS 110: Introduction to Computer Programming. Exam announcements. Programming assertions revisited. An extended example: mystery

Outline. 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 information

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

COMP200 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 information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming File as Input; Exceptions; while loops; Basic Arrays Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

More information

CS244 Advanced Programming Applications

CS244 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 information

Building Java Programs Chapter 6

Building 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 information

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

Wentworth 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 information

Unit 10: exception handling and file I/O

Unit 10: exception handling and file I/O Unit 10: exception handling and file I/O Using File objects Reading from files using Scanner Writing to file using PrintStream not in notes 1 Review What is a stream? What is the difference between a text

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 14: OCT. 25TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 14: OCT. 25TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 14: OCT. 25TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments No new homework this week. Please make up the homework 1 5 & class exercises this week.

More information

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 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 information

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

File 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 information

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

EXCEPTION 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 information

Exception Handling. Handling bad user input. Dr. Siobhán Drohan Maireád Meagher. Produced by:

Exception Handling. Handling bad user input. Dr. Siobhán Drohan Maireád Meagher. Produced by: Exception Handling Handling bad user input Produced by: Dr. Siobhán Drohan Maireád Meagher Department of Computing and Mathematics http://www.wit.ie/ ShopV4.0 (or any version) When testing it, did you

More information

Chapter 4 Classes in the Java Class Libraries

Chapter 4 Classes in the Java Class Libraries Programming Fundamental I ACS-1903 Chapter 4 Classes in the Java Class Libraries 1 Random Random The Random class provides a capability to generate pseudorandom values pseudorandom because the stream of

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

More information

Reading Text Files. 1 Reading from text files: Scanner

Reading Text Files. 1 Reading from text files: Scanner Reading Text Files 1 Reading from text files: Scanner Text files, whether produced by a program or with a text editor, can be read by a program using class Scanner, part of the java.util package. We open

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Computer Science is...

Computer 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

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018 Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)

More information

Files. Reading data from files. File class. Compiler error with files. Checked exceptions. Exceptions. Readings:

Files. Reading data from files. File class. Compiler error with files. Checked exceptions. Exceptions. Readings: Reading data from files Files Creating a Scanner for a file, general syntax: Scanner = new Scanner(new File("")); Example: Scanner input = new Scanner(new File("numbers.txt")); Readings:

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution https://www.dignitymemorial.com/obituaries/brookline-ma/adele-koss-5237804 Topic 11 Scanner object, conditional execution Logical thinking and experience was as important as theory in using the computer

More information

A token is a sequence of characters not including any whitespace.

A token is a sequence of characters not including any whitespace. Scanner A Scanner object reads from an input source (keyboard, file, String, etc) next() returns the next token as a String nextint() returns the next token as an int nextdouble() returns the next token

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 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 information

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI Outline Chapter 3 Using APIs 3.1 Anatomy of an API 3.1.1 Overall Layout 3.1.2 Fields 3.1.3 Methods 3.2 A Development Walkthrough 3.2.1 3.2.2 The Mortgage Application 3.2.3 Output Formatting 3.2.4 Relational

More information

Building Java Programs

Building 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 information

Object Oriented Programming. Java-Lecture 1

Object Oriented Programming. Java-Lecture 1 Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

More information

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

More information

Computational Expression

Computational 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 information

CS Programming I: File Input / Output

CS Programming I: File Input / Output CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624

More information

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

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Text User Interfaces. Keyboard IO plus

Text 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 information

Repetition. Chapter 6

Repetition. Chapter 6 Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

More information

Repetition. Chapter 6

Repetition. Chapter 6 Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

More information

Lecture 8 " INPUT " Instructor: Craig Duckett

Lecture 8  INPUT  Instructor: Craig Duckett Lecture 8 " INPUT " Instructor: Craig Duckett Assignments Assignment 2 Due TONIGHT Lecture 8 Assignment 1 Revision due Lecture 10 Assignment 2 Revision Due Lecture 12 We'll Have a closer look at Assignment

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Object-Oriented Programming in Java

Object-Oriented Programming in Java CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio

More information

Building Java Programs

Building 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 information

9. Java Errors and Exceptions

9. Java Errors and Exceptions Errors and Exceptions in Java 9. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1, 4.5 2 Interactive Programs with Scanner reading: 3.3-3.4 Interactive programs We have written programs that print console

More information

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #5

More information

CS 112 Introduction to Programming

CS 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 information

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

Wentworth 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 information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);

More information

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Loops. 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 information

CS 211: Existing Classes in the Java Library

CS 211: Existing Classes in the Java Library CS 211: Existing Classes in the Java Library Chris Kauffman Week 3-2 Logisitics Logistics P1 Due tonight: Questions? Late policy? Lab 3 Exercises Thu/Fri Play with Scanner Introduce it today Goals Class

More information

CS 112 Introduction to Programming

CS 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 information

CS 112 Introduction to Programming

CS 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 information

Introduction to Programming Using Java (98-388)

Introduction 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 information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement Operators The while Loop Using the while Loop for Input Validation The do-while Loop

More information

Example Program. public class ComputeArea {

Example Program. public class ComputeArea { COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

More information

Chapter 2: Basic Elements of Java

Chapter 2: Basic Elements of Java Chapter 2: Basic Elements of Java TRUE/FALSE 1. The pair of characters // is used for single line comments. ANS: T PTS: 1 REF: 29 2. The == characters are a special symbol in Java. ANS: T PTS: 1 REF: 30

More information

Java Errors and Exceptions. Because Murphy s Law never fails

Java Errors and Exceptions. Because Murphy s Law never fails Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 6 Lecture 6-2: Line-Based File Input reading: 6.3-6.5 2 Hours question Given a file hours.txt with the following contents: 123 Ben 12.5 8.1 7.6 3.2 456 Greg 4.0 11.6 6.5

More information

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

boolean, 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 information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Chapter 4: Loops and Files

Chapter 4: Loops and Files Chapter 4: Loops and Files Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 4 discusses the following main topics: The Increment and Decrement

More information

COMP102: 181. Menu. More while loops. Admin: Test. Peter Andreae

COMP102: 181. Menu. More while loops. Admin: Test. Peter Andreae Menu COMP102: 181 More while loops Admin: Test Designing loops with numbers COMP102: 182 When the number of steps is known at the beginning of the loop: int count = 0; int num = 1; while ( count < number)

More information

CS Programming I: File Input / Output

CS Programming I: File Input / Output CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455

More information

Lesson 7 Part 2 Flags

Lesson 7 Part 2 Flags Lesson 7 Part 2 Flags A Flag is a boolean variable that signals when some condition exists in a program. When a flag is set to true, it means some condition exists When a flag is set to false, it means

More information

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Exception Handling. CSE 114, Computer Science 1 Stony Brook University Exception Handling CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation When a program runs into a exceptional runtime error, the program terminates abnormally

More information

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O) 116 7. Java Input/Output User Input/Console Output, File Input and Output (I/O) 117 User Input (half the truth) e.g. reading a number: int i = In.readInt(); Our class In provides various such methods.

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 9 Exercise

More information

Java I/O and Control Structures

Java I/O and Control Structures Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying

More information

Review 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 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 information

Advanced Java Concept Unit 1. Mostly Review

Advanced Java Concept Unit 1. Mostly Review 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

More information

A Quick and Dirty Overview of Java and. Java Programming

A Quick and Dirty Overview of Java and. Java Programming Department of Computer Science New Mexico State University. CS 272 A Quick and Dirty Overview of Java and.......... Java Programming . Introduction Objectives In this document we will provide a very brief

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 Randomness Lack of predictability: don't know what's coming next Random process: outcomes do not

More information

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education AP Computer Science Return values, Math, and double Distance between points Write a method that given x and y coordinates for two points prints the distance between them If you can t do all of it, pseudocode?

More information

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

Type boolean. Building Java Programs. Recap: Type boolean. Short-circuit evaluation. De Morgan's Law. Boolean practice questions. Building Java Programs Chapter 5 Lecture 5-4: More boolean, Assertions, do/while loops Type boolean reading: 5.3 reading: 5.3, 5.4, 5.1 1 Recap: Type boolean boolean: A logical type whose values are true

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

JAVA Ch. 4. Variables and Constants Lawrenceville Press

JAVA Ch. 4. Variables and Constants Lawrenceville Press JAVA Ch. 4 Variables and Constants Slide 1 Slide 2 Warm up/introduction int A = 13; int B = 23; int C; C = A+B; System.out.print( The answer is +C); Slide 3 Declaring and using variables Slide 4 Declaring

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

1. An operation in which an overall value is computed incrementally, often using a loop.

1. 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 information

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/ Topic 15 boolean methods and random numbers "It is a profoundly erroneous truism,

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 11 I/O File Input and Output Reentering data all the time could get tedious for the user. The data can be saved to

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information