CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement



Similar documents
CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Sample CSE8A midterm Multiple Choice (circle one)

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Conditional Statements Summer 2010 Margaret Reid-Miller

J a v a Quiz (Unit 3, Test 0 Practice)

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Topic 11 Scanner object, conditional execution

CS 106 Introduction to Computer Science I

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Building Java Programs

LAB4 Making Classes and Objects

Install Java Development Kit (JDK) 1.8

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Object Oriented Software Design

Introduction to Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

ECE 122. Engineering Problem Solving with Java

AP Computer Science Static Methods, Strings, User Input

Part I. Multiple Choice Questions (2 points each):

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

COMP 110 Prasun Dewan 1

Homework/Program #5 Solutions

Java Crash Course Part I

Chapter 2 Introduction to Java programming

Introduction to Python

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

In this Chapter you ll learn:

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

AP Computer Science Java Subset

Some Scanner Class Methods

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Moving from CS 61A Scheme to CS 61B Java

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Introduction to Object-Oriented Programming

Software Engineering Techniques

Introduction to Programming

LOOPS CHAPTER CHAPTER GOALS

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Basics of Java Programming Input and the Scanner class

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Introduction to Java. CS 3: Computer Programming in Java

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Object Oriented Software Design

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Arrays in Java. Working with Arrays

Java Basics: Data Types, Variables, and Loops

Boolean Expressions & the if Statement

Lecture 2 Notes: Flow of Control

Java Classes. GEEN163 Introduction to Computer Programming

Lecture 1 Introduction to Java

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Conditionals (with solutions)

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

Comp 248 Introduction to Programming

Chapter 3 Operators and Control Flow

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

VB.NET Programming Fundamentals

The following program is aiming to extract from a simple text file an analysis of the content such as:

Example of a Java program

Programming in Java Course Technology, a part of Cengage Learning.

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

For live Java EE training, please see training courses

Chapter 8 Selection 8-1

Program Logic to Java GEEN163

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

13 File Output and Input

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Crash Course in Java

Java 進 階 程 式 設 計 03/14~03/21

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

C++FA 5.1 PRACTICE MID-TERM EXAM

Interactive Applications (CLI) and Math

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Selection Statements

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Lecture 5: Java Fundamentals III

Computer Programming I

(Eng. Hayam Reda Seireg) Sheet Java

Conditions & Boolean Expressions

D06 PROGRAMMING with JAVA

Statements and Control Flow

Arrays. Introduction. Chapter 7

JavaScript: Control Statements I

Transcription:

CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement

Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2

Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit problem fixed) p2: Find Parking due Oct 5

Boolean Expressions

Review: Variables of the boolean Primitive Data Type have values true or false! boolean p;! p = true;! p = false;! boolean q=false;! p = q;!

A boolean Expression Evaluates to true or false! boolean p=true, q=false, x;! x =!p;!!!//not p! x = p q;!!//p OR q! x = p && q;!!//p AND q! x = (p q) && (!q); Logical Operators AKA Conditional Operators http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

Constructing a boolean Expression with Equality/Relational Operators! int x=3, y=4;! boolean p;! p = (x<y);!!!//less Than! p = (x<=y);!!//less Than or Equal! p = (x==y);!!//equal! p = (x!=y);!!//not equal! p = (x>=y);!!//greater Than or Equal! p = (x>y);!!!//greater Than!

Complex Boolean Expressions! int x=3, y=4;! boolean p;!! p = (x>=3) && (y!=0);

Advanced Topic: Short-Circuit Evaluation of Expressions! int x=3, y=0;! boolean p;!! p = (y!=0) && ((x/y) > 1);!! If the left-hand side of the && evaluates to false Then the right-hand side is never evaluated, avoiding the division-by-zero

Avoid Reference Variables in boolean Expressions (Unless You Really Want to Compare Memory Addresses) import java.util.scanner;! public class MyClass {! public static void main(string[] args) {! }!!Scanner stdin = new Scanner(System.in);!!String u = stdin.next();!!string v = stdin.next();!!boolean p = (u==v); }!!//Always false!!!!

How to compare String content import java.util.scanner;! public class MyClass {! }! public static void main(string[] args) {! }!!Scanner stdin = new Scanner(System.in);!!String u = stdin.next();!!string v = stdin.next();!!boolean p = u.equals(v); //Compares String content!

Decision-making with the if Statement

The if Statement So far our programs have (well mostly) executed statements sequentially in the order of their appearance in a method! Real programs make decisions, executing different blocks of statements depending upon the value of a boolean expression

Syntax of the if Statement if (condition) Statement;!! Statement is executed only if condition evaluates true, otherwise it s skipped A condition is just a Boolean Expression used in a conditional statement

Very Simple Example boolean p;!.!.! //Calculate a value for p!.! if (p) System.out.println( p is true! );!.!.!.!!

Example if Statements int x = stdin.nextint();! int y = stdin.nextint();! if (x == y) System.out.println( x equals y);! if (x < y) System.out.println( x less than y );! if (x > y) System.out.println( x greater than y );!

More if Examples int x = stdin.nextint();! String s = ;! if (x < 0) s = Negative ;! if (x == 0) s = Zero ;! if (x > 0) s = Positive ;! System.out.printf( x is %s\n, s);!

The if Statement with a Code Block int x = stdin.nextint();! int y = stdin.nextint();! if (x <= y) {!!System.out.println( x equals y);!!system.out.printf( x = %d\n, x);!!system.out.printf( y = %d\n, y);! }!! Code block is a set of statements enclosed by braces The entire code block is executed when condition is true The entire code block is skipped when condition is false

Nested if Statements.!.!.! int x = stdin.nextint();! String s = stdin.next();! int y = stdin.nextint();! int z = 0;! if (y!=0) {!!System.out.println( y is non-zero );!!if (s.equals( / )) {!!!z = x / y;!!}! }!

if else

The if else Statement if (condition) statement1; else statement2; Condition is just a Boolean Expression Statement1 executed only if condition evaluates true Statement2 executed only if condition evaluates false

Code Blocks Work Fine if (condition) {.. //Multiple statements may appear here. } else {.. //And/or here. } You may use a code block for either or both statements

Example if else Statement if (y == 0) {! } else {! }!!System.out.println( Error: y == 0 );!!System.exit(-1);!//Stop this program!!!double z = x/y;!!system.out.printf( z = %f\n,z);!

Nested if else Statement if (condition1) statement1; else if (condition2) statement2; Either statement may be another if statement Statement1 executed only if condition1 is true Statement2 executed only if condition1 is false and condition2 is true

Beware the Dangling else!!! if (condition1) if (condition2) statement1; else statement2; Java always associates an else with the most recent if! The else above is associated with the second if! Thus, statement2 is executed only if condition1 is true and condition2 is false!!!

Avoid the Dangling else by always using Code Blocks if (condition1) { if (condition2) statement1; } else { statement2; } Use code-blocks to avoid death by dangling else! Here, statement2 is executed only if condition1 is false The code blocks communicate your intent to Java and other programmers reading your code

If you insist on using the dangling else, then code it neatly! if (condition1) if (condition2) statement1; else statement2; Use indentation to avoid confusing other programmers This does what it looks like it might do statement2 is executed only if condition1 is true and condition2 is false

Dangling else Sometimes Appears on Exams if (condition1) if (condition2) statement1; else { } statement2; While you won t code a dangling else You will encounter it written by other programmers The else above is associated with the second if This indentation is misleading!!! Java ignores the indentation!!!

The return Statement

A Method May Return a Value to its Caller class Dog {! }!! private boolean gooddog; public boolean getgooddog() {!!return gooddog;! }!!//Instance variable!

Caller s May Use Returned Values in Expressions!Dog katy = new Dog( Katy );!!if (!katy.getgooddog()) katy.train();!

A void Method Never Returns a Value class Dog {! }! public void speak() {! }!!System.out.println( Woof! );!

The return Statement is Useful Even in void Methods class Dog {! boolean gooddog;! public void bark() {!!if (gooddog) {!! System.out.println( Wag more, bark less. );! return;!!}!!system.out.println( Woof! );! }! }!

Invoking (calling) a void method!dog katy = new Dog( Katy );!!katy.train();!

Review: Invoking (calling) static methods!!double x = Math.sqrt(3.14);!System.out.println(x);!!//Returns double! //void!