BLOCK STRUCTURE. class block main method block do-while statement block if statement block. if statement block. Block Structure Page 1

Similar documents
SCOPE. public class ABC { public static void main( String args [ ] ) { Not accessible outside the block. Local to this block; accessible within it

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

CSC 1051 Data Structures and Algorithms I

Chapter 3. Selections

Introduction to Computer Science Unit 2. Exercises

Introduction to Java Applications

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.

Algorithms and Conditionals

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

COMP 110 Programming Exercise: Simulation of the Game of Craps

Practice Midterm 1 Answer Key

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

DEFECT TESTING. Since the goal of each test run is to uncover another error, a successful test run is one that causes your program to fail.

THE JAVA FOR STATEMENT

Introduction to Java Programs for Packet #4: Classes and Objects

Selection and Repetition Revisited

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Logic & program control part 2: Simple selection structures

CS111: PROGRAMMING LANGUAGE II

In this lab, you will learn more about selection statements. You will get familiar to

AP CS Unit 3: Control Structures Notes

Introduction to the Java Basics: Control Flow Statements

JOptionPane Dialogs. javax.swing.joptionpane is a class for creating dialog boxes. Has both static methods and instance methods for dialogs.

COMP 202. Java in one week

Selection Statements and operators

CS1150 Principles of Computer Science Loops (Part II)

Selection Statements and operators

Practice Midterm 1. Problem Points Score TOTAL 50

COMP 202 Java in one week

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

Java Coding 3. Over & over again!

Selection and Repetition

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Object-Based Programming. Programming with Objects

Selection and Repetition Revisited

Supplementary Test 1

Course PJL. Arithmetic Operations

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

CS 106 Introduction to Computer Science I

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

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

4 WORKING WITH DATA TYPES AND OPERATIONS

Decisions: Logic Java Programming 2 Lesson 7

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Introduction to Computer Science Unit 2. Notes

1 Short Answer (2 Points Each)

Full file at

H212 Introduction to Software Systems Honors

Unit 1 Lesson 4. Introduction to Control Statements

CONDITIONAL EXECUTION

Chapter 4: Control structures. Repetition

Chapter 4 Classes in the Java Class Libraries

OBJECTS AND CLASSES. Examples. You and I are instances of the class of objects known as people.

Course Outline. Introduction to java

Chapter 1 Lab Algorithms, Errors, and Testing

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Conditional Programming

! 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

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Chapter 4: Control structures

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

Chapter 3 Selection Statements

Java I/O and Control Structures

CSC 1051 Algorithms and Data Structures I. Final Examination December 18, Name:

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

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

Java I/O and Control Structures Algorithms in everyday life

Introduction to Computer Science Unit 3. Programs

Introduction to Java Applications

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Programming Practice (vs Principles)

Chapter 4 Introduction to Control Statements

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Full file at

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

NATIONAL UNIVERSITY OF SINGAPORE

download instant at

COE 212 Engineering Programming. Welcome to Exam I Thursday June 21, Instructor: Dr. Wissam F. Fawaz

COE 211 Computer Programming. Welcome to Exam I Tuesday March 13, 2018

Control Statements: Part 1

What two elements are usually present for calculating a total of a series of numbers?

Chapter 2: Using Data

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Chapter 2 Primitive Data Types and Operations

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

4. Java language basics: Function. Minhaeng Lee

for Diane Christie University of Wisconsin Stout

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

2/2/18. Assignment 2 is due Wednesday 14 February at 11:59pm. Reading for Monday s lecture is the remainder of Chapter 7 and all of Chapter 8

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Bjarne Stroustrup. creator of C++

Transcription:

BLOCK STRUCTURE A block is a bundle of statements in a computer program that can include declarations and executable statements. A programming language is block structured if it (1) allows blocks to be created and (2) allows blocks to be nested within other blocks. Many modern programming languages, including Java, are block structured. Java blocks are identified and delimited by curly braces () and nesting can be carried on to several levels statement blocks can be nested within method blocks; method can be nested within class blocks; and class blocks may be nested within other class blocks. When a block is nested within another, we call the surrounding block the outer block and the block nested within it the inner block. By drawing a line around each block and omitting the details (such as code and declarations) you can clarify the hierarchical block structure of code. Such a simplified drawing is called a contour map. Example Connecting the delimiting braces of each block on this Java code leads to the contour map shown on the right. The two if statement blocks are inner to the do-while statement block but separate from each other. The do-while statement is outer to both if statement blocks. public class TimesDrill public static void main( String args [ ] ) int a, b; // times operands int ansr; // right answer int ansu; // user's answer int score; // user's score String s; // output string Scanner scanner = new Scanner( System.in ); System.out.println( "Practice multiplication" ); System.out.println( "To quit, enter -1" ); score = 0; // initialize score do a = (int)( Math.random( )*11 ); b = (int)( Math.random( )*11 ); s = a + " X " + b + " = "; System.out.print( s + "? " ); ansr = a * b; // compute right answer ansu = scanner.nextint( ); // get user's answer if ( ansu == -1 ) // user wants to quit System.out.println( "Goodbye" ); break; // quit if ( ansu!= ansr ) // user answered wrong System.out.print( "Sorry, " + s + ansr ); break; // quit // user entered a correct answer so add one to // score and encourage continuing score++; System.out.println(score+" right. Keep going!"); while ( true ); class block main method block do-while statement block if statement block if statement block Block Structure Page 1

This application has four blocks labeled A, B, C and D. The contour map is shown to the right. import java.util.scanner; import java.text.decimalformat; import static javax.swing.joptionpane.*; C while statment block D if statment block public class PayWithOverTime static DecimalFormat df = new DecimalFormat( " $#,###.00" ); // declare data String input, prompt, output; prompt = "Enter name, wage, hours separated by commas"; // read until user cancels dialog while ( ( input = showinputdialog( prompt ) )!= null ) // user entered data so build scanner and set delimiter Scanner scan = new Scanner( input ); scan.usedelimiter( "," ); // scan worker's name, hourly wage and hours worked String name = scan.next( ); double wage = scan.nextdouble( ); double hours = scan.nextint( ); // calculate worker's regular pay double pay = hours * wage; if ( hours > 40 ) // if overtime // add half pay for each overtime hour A B C D double extrapay; extrapay = (hours - 40) * wage * 0.5; pay = pay + extrapay; output = "Pay " + name + df.format( pay ); showmessagedialog( null, output ); Block Structure Page 2

This application has five blocks. In its contour, the four method blocks B, C, D and E are stacked on top of each other and surrounded by the class block A. import static javax.swing.joptionpane.*; import java.text.decimalformat; C method block D method block E method block public class CircleMethods static DecimalFormat df = new DecimalFormat( "0.000" ); // declare data double radius, area; B radius = inputradius( ); area = calcarea( radius ); printresults( radius, area ); A public static double inputradius( ) String msg = "Enter circle's radius"; C return Double.parseDouble( showinputdialog( msg ) ); public static double calcarea( double radius ) D return Math.PI * Math.pow( radius, 2 ); public static void printresults( double r, double a ) String out = "Circle with radius " + df.format( r ) E + "\nhas area = " + df.format( a ); showmessagedialog( null, out ); Block Structure Page 3

Application DiceToss has six blocks, including an inner class nested within the application class. The contour map at right pictures how blocks E and F are inner to D; B, C and D are inner to A; and public class DiceToss B new DiceToss( ); // call app constructor C constructor block D class block E constructor block F method block A public DiceToss( ) // app constructor Die die1 = new Die( ); // build one die Die die2 = new Die( ); // build another die1.roll( ); // roll them C die2.roll( ); int sum = die1.faceup + die2.faceup; System.out.println( "Roll is " + sum ); // A Die object models a 6-sided die used for dice games. public class Die public int faceup; // number shown facing up D public Die( ) E roll( ); // explicit constructor public void roll( ) // roll the die // randomly select a number from 1 to 6 F faceup = (int)(math.random( ) * 6 + 1); Block Structure Page 4

Exercises 1. Mark each block in the following Java program. HINT: any curly brace () delimited code is a block because it could potentially contain data declarations even if it doesn t. Draw its contour map. public class DukeandEarl final double DUKE_FTP = 0.5; final double EARL_FTP = 0.5; String shooter, winner; // Duke and Earl flip a coin to see who shoots first shooter = ( Math.random( ) < 0.5 )? "Duke" : "Earl"; winner = "nobody"; while ( winner.equals( "nobody" ) ) System.out.print( shooter + " shoots and " ); if ( shooter.equals( "Duke" ) ) if (Math.random( ) <= DUKE_FTP ) System.out.println( "HITS!" ); winner = "Duke"; else System.out.println( "misses" ); shooter = "Earl"; else // shooter is Earl if (Math.random( ) <= EARL_FTP ) System.out.println( "HITS!" ); winner = "Earl"; else System.out.println( "misses" ); shooter = "Duke"; System.out.println( winner + " WINS!!!" ); Block Structure Page 5