Building Java Programs



Similar documents
Building Java Programs

Topic 11 Scanner object, conditional execution

Statements and Control Flow

Building Java Programs

Iteration CHAPTER 6. Topic Summary

Building Java Programs

Building Java Programs

Arrays. Introduction. Chapter 7

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

COMP 110 Prasun Dewan 1

Unit 6. Loop statements

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Introduction to Java

Java Basics: Data Types, Variables, and Loops

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

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

Sample CSE8A midterm Multiple Choice (circle one)

The While Loop. Objectives. Textbook. WHILE Loops

Building Java Programs

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

1.3 Conditionals and Loops

Conditional Statements Summer 2010 Margaret Reid-Miller

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

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

LOOPS CHAPTER CHAPTER GOALS

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

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?

AP Computer Science Java Subset

Topic 16 boolean logic

Example of a Java program

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

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

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

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

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

Object Oriented Software Design

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

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

Web Programming Step by Step

Introduction to Java. CS 3: Computer Programming in Java

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

CS 106 Introduction to Computer Science I

1. Writing Simple Classes:

CS170 Lab 11 Abstract Data Types & Objects

Introduction to. Marty Stepp University of Washington

Building Java Programs

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

While Loop. 6. Iteration

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

if and if-else: Part 1

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

Homework/Program #5 Solutions

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

Factorizations: Searching for Factor Strings

Chapter 8 Selection 8-1

VB.NET Programming Fundamentals

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Computer Programming I

Lecture 2 Notes: Flow of Control

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

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Basic Programming and PC Skills: Basic Programming and PC Skills:

CS106A, Stanford Handout #38. Strings and Chars

Chapter 5. Recursion. Data Structures and Algorithms in Java

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Object Oriented Software Design

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

Hooray for the Hundreds Chart!!

In this Chapter you ll learn:

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

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

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Building Java Programs

Term Project: Roulette

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

AP Computer Science File Input with Scanner

Project 2: Bejeweled

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Python Programming: An Introduction To Computer Science

Interactive Applications (CLI) and Math

Building Java Programs

Recursion and Recursive Backtracking

Chapter 2 Introduction to Java programming

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Contents. 9-1 Copyright (c) N. Afshartous

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Moving from CS 61A Scheme to CS 61B Java

Maria Litvin Phillips Academy, Andover, Massachusetts. Gary Litvin Skylight Publishing, Andover, Massachusetts

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Computational Mathematics with Python

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Lecture 1 Introduction to Java

Transcription:

Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2007. They may not be rehosted, sold, or modified without expressed permission from the authors. All rights reserved. 1

Lecture outline Lecture 9 conditional execution the if statement and the if/else statement relational expressions nested if/else statements Lecture 10 subtleties of conditional execution factoring if/else code fencepost loops methods with conditional execution revisiting return values 2

if/else statements suggested reading: 4.2 3

The if statement if statement: A Java statement that executes a block of statements only if a certain condition is true. If the condition is not true, the block of statements is skipped. General syntax: if (<condition>) { <statement> ; <statement> ;... <statement> ; Example: double gpa = console.nextdouble(); if (gpa >= 2.0) { System.out.println("Your application is accepted."); 4

if statement flow diagram 5

The if/else statement if/else statement: A Java statement that executes one block of statements if a certain condition is true, and a second block of statements if it is false. General syntax: if (<condition>) { <statement(s)> ; else { <statement(s)> ; Example: double gpa = console.nextdouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); else { System.out.println("Your application is denied."); 6

if/else flow diagram 7

Relational expressions The <condition> used in an if or if/else statement is the same kind seen in a for loop. for (int i = 1; i <= 10; i++) { The conditions are actually of type boolean, seen in Ch. 5. These conditions are called relational expressions and use one of the following six relational operators: Operator Meaning Example Value == equals 1 + 1 == 2 true!= does not equal 3.2!= 2.5 true < less than 10 < 5 false > greater than 10 > 5 true <= less than or equal to 126 <= 100 false >= greater than or equal to 5.0 >= 5.0 true 8

Evaluating rel. expressions Relational operators have lower precedence than math operators. Example: 5 * 7 >= 3 + 5 * (7-1) 5 * 7 >= 3 + 5 * 6 35 >= 3 + 30 35 >= 33 true Relational operators cannot be "chained" as they can in algebra. Example: 2 <= x <= 10 true <= 10 error! 9

if/else question Write code to read a number from the user and print whether it is even or odd using an if/else statement. Example executions: Type a number: 42 Your number is even Type a number: 17 Your number is odd 10

Loops with if/else Loops can be used with if/else statements: int nonnegatives = 0, negatives = 0; for (int i = 1; i <= 10; i++) { int next = console.nextint(); if (next >= 0) { nonnegatives++; else { negatives++; public static void printevenodd(int max) { for (int i = 1; i <= max; i++) { if (i % 2 == 0) { System.out.println(i + " is even"); else { System.out.println(i + " is odd"); 11

Nested if/else statements Nested if/else statement: A chain of if/else that can select between many different outcomes based on several conditions. General syntax: if (<condition>) { <statement(s)> ; else if (<condition>) { <statement(s)> ; else { <statement(s)> ; Example: if (number > 0) { System.out.println("Positive"); else if (number < 0) { System.out.println("Negative"); else { System.out.println("Zero"); 12

Nested if/else variations A nested if/else can end with an if or an else. If it ends with else, one of the code paths must be taken. If it ends with if, the program might not execute any path. Example ending with else: if (place == 1) { System.out.println("You win the gold medal!"); else if (place == 2) { System.out.println("You win a silver medal!"); else if (place == 3) { System.out.println("You earned a bronze medal."); Are there any cases where this code will not print a message? How could we modify it to print a message to non-medalists? 13

Nested if/else flow diagram if (<condition>) { <statement(s)> ; else if (<condition>) { <statement(s)> ; else { <statement(s)> ; 14

Nested if/else/if flow diagram if (<condition>) { <statement(s)> ; else if (<condition>) { <statement(s)> ; else if (<condition>) { <statement(s)> ; 15

Sequential if flow if (<condition>) { <statement(s)> ; if (<condition>) { <statement(s)> ; if (<condition>) { <statement(s)> ; 16

Structures of if/else code Choose 1 of many paths: (conditions are mutually exclusive) if (<condition>) { <statement(s)>; else if (<condition>) { <statement(s)>; else { <statement(s)>; Choose 0, 1, or many of many paths: (conditions/actions are independent of each other) if (<condition>) { <statement(s)>; if (<condition>) { <statement(s)>; if (<condition>) { <statement(s)>; Choose 0 or 1 of many paths: (conditions are mutually exclusive and any action is optional) if (<condition>) { <statement(s)>; else if (<condition>) { <statement(s)>; else if (<condition>) { <statement(s)>; 17

Which nested if/else to use? Which if/else construct is most appropriate to perform each of the following tasks? Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8). Printing whether a number is even or odd. Printing whether a user is lower-class, middle-class, or upperclass based on their income. Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5. Printing a user's grade of A, B, C, D, or F based on their percentage in the course. 18

Which nested if/else to use? Which if/else construct is most appropriate to perform each of the following tasks? Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8). nested if / else if Printing whether a number is even or odd. simple if / else Printing whether a user is lower-class, middle-class, or upperclass based on their income. nested if / else if / else Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5. sequential if / if / if Printing a user's grade of A, B, C, D, or F based on their percentage in the course. nested if / else if / else if / else if / else 19

How to comment: if/else Comments on an if statement don't need to describe exactly what the if statement is testing. Instead, they should describe why you are performing that test, and/or what you intend to do based on its result. Bad example: // Test whether student 1's GPA is better than student 2's if (gpa1 > gpa2) { // print that student 1 had the greater GPA System.out.println("The first student had the greater GPA."); else if (gpa2 > gpa1) { // print that student 2 had the greater GPA System.out.println("The second student's GPA was higher."); else { // there was a tie System.out.println("There has been a tie!"); Better example: // Print a message about which student had the higher grade point average. if (gpa1 > gpa2) { System.out.println("The first student had the greater GPA."); else if (gpa2 > gpa1) { System.out.println("The second student's GPA was higher."); else { // gpa1 == gpa2 (a tie) System.out.println("There has been a tie!"); 20

How to comment: if/else 2 If an if statement's test is straightforward, and if the actions to be taken in the bodies of the if/else statement are very different, sometimes putting comments on the bodies themselves is more helpful. Example: if (guessagain == 1) { // user wants to guess again; reset game state and // play another game System.out.println("Playing another game."); score = 0; resetgame(); play(); else { // user is finished playing; print their best score System.out.println("Thank you for playing."); System.out.println("Your score was " + score); 21

Math.max/min vs. if/else Many if/else statements that choose the larger or smaller of 2 numbers can be replaced by a call to Math.max or Math.min. int z; // z should be larger of x, y if (x > y) { z = x; else { z = y; int z = Math.max(x, y); double d = a; // d should be smallest of a, b, c if (b < d) { d = b; if (c < d) { d = c; double d = Math.min(a, Math.min(b, c)); 22

Lecture outline Lecture 9 conditional execution the if statement and the if/else statement relational expressions nested if/else statements Lecture 10 subtleties of conditional execution factoring if/else code fencepost loops methods with conditional execution revisiting return values 23

Subtleties of conditional execution suggested reading: 4.3 24

Factoring if/else code factoring: extracting common/redundant code Factoring if/else code reduces the size of the if and else statements and can sometimes eliminate the need for if/else altogether. Example: int x; if (a == 1) { x = 3; else if (a == 2) { x = 5; else { // a == 3 x = 7; int x = 2 * a + 1; 25

Code in need of factoring The following example has a lot of redundant code in the if/else: if (money < 500) { System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextint(); else if (money < 1000) { System.out.println("You have, $" + money + " left."); System.out.print("Consider betting moderately."); System.out.print("How much do you want to bet? "); bet = console.nextint(); else { System.out.println("You have, $" + money + " left."); System.out.print("You may bet liberally."); System.out.print("How much do you want to bet? "); bet = console.nextint(); 26

Code after factoring Factoring tips: If the start of each branch is the same, move it before the if/else. If the end of each branch is the same, move it after the if/else. System.out.println("You have, $" + money + " left."); if (money < 500) { System.out.print("Caution! Bet carefully."); else if (money < 1000) { System.out.print("Consider betting moderately."); else { System.out.print("You may bet liberally."); System.out.print("How much do you want to bet? "); bet = console.nextint(); 27

Fencepost loops suggested reading: 4.1 28

The fencepost problem Problem: Write a static method named printnumbers that prints each number from 1 to a given maximum, separated by commas. For example, the method call: printnumbers(5) should print: 1, 2, 3, 4, 5 Let's write a solution to this problem... 29

Flawed solution 1 A flawed solution: public static void printnumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(i + ", "); System.out.println(); // to end the line of output Output from printnumbers(5): 1, 2, 3, 4, 5, 30

Flawed solution 2 Another flawed solution: public static void printnumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(", " + i); System.out.println(); // to end the line of output Output from printnumbers(5):, 1, 2, 3, 4, 5 31

Fence post analogy We print n numbers but need only n - 1 commas. This problem is similar to the task of building a fence with lengths of wire separated by posts. often called a fencepost problem If we repeatedly place a post and wire, the last post has an extra dangling wire. A flawed algorithm: for (length of fence): place some post. place some wire. 32

Fencepost loop The solution is to add an extra statement outside the loop that places the inital "post." This is sometimes also called a fencepost loop or a "loop-and-a-half" solution. The revised algorithm: place a post. for (length of fence - 1): place some wire. place some post. 33

Fencepost method solution A version of printnumbers that works: public static void printnumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); System.out.println(); // to end the line of output OUTPUT from printnumbers(5): 1, 2, 3, 4, 5 34

Fencepost practice problem Write a method named printfactors that, when given a number, prints its factors in the following format (using an example of 24 for the parameter value): [1, 2, 3, 4, 6, 8, 12, 24] 35

Fencepost practice problem Write a Java program that reads a base and a maximum power and prints all of the powers of the given base up to that max, separated by commas. Base: 2 Max exponent: 9 The first 9 powers of 2 are: 2, 4, 8, 16, 32, 64, 128, 256, 512 36

Methods with if/else suggested reading: 4.5 37

if/else with return Methods can be written to return different values under different conditions using if/else statements: public static int min(int a, int b) { if (a > b) { return a; else { return b; An example that maps chess board squares to colors: public static Color chessboardcolor(int row, int column) { if ((row + column) % 2 == 0) { return Color.WHITE; else { return Color.BLACK; 38

More examples Another example that returns the first word in a string: public static String firstword(string s) { int index = s.indexof(" "); if (index >= 0) { return s.substring(0, index); else { // only one word in String return s; It is an error not to return a value in every path: public static int min(int a, int b) { if (a > b) { return b; // Error; not all code paths return a value. // What if a <= b? 39

All code paths must return The following code does not compile: public static int min(int a, int b) { if (a >= b) { return b; else if (a < b) { return a; It produces the "Not all paths return a value" error. To our eyes, it is clear that all paths (greater, equal, less) do return a value. But the compiler thinks that if/else/if code might choose not to execute any branch, so it refuses to accept this code. How can we fix it? 40

for loops with if/else return Methods with loops that return values must consider the case where the loop does not execute the return. public static int indexof(string s, char c) { for (int i = 0; i < s.length(); i++) { if (s.charat(i) == c) { return i; // error; what if c does not occur in s? A better version that returns -1 when c is not found: public static int indexof(string s, char c) { for (int i = 0; i < s.length(); i++) { if (s.charat(i) == c) { return i; return -1; // not found 41

if/else return question Write a method named numunique that accepts two integers as parameters and returns how many unique values were passed. For example, numunique(3, 7) returns 2 because 3 and 7 are two unique numbers, but numunique(4, 4) returns 1 because 4 and 4 only represent one unique number. Write a method named countfactors that returns the number of factors of an integer. For example, countfactors(60) returns 11 because 1, 2, 3, 4, 5, 6, 10, 15, 20, 30, and 60 are factors of 60. Modify the piglatinword and encode/decode methods seen previously so that they return their results rather than printing them. 42

Method return question Write a program that prompts the user for a maximum integer and prints out a list of all prime numbers up to that maximum. Here is an example log of execution: Maximum number? 50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 14 total primes 43