Java How to Program, 9/e

Transcription

1 Java How to Program, 9/e Education, Inc. All Rights Reserved. 1 Any computing problem can be solved by executing a series of actions in a specific order. An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which these actions execute The rise-and-shine algorithm followed by one executive for getting out of bed and going to work: (1) Get out of bed; (2) take off pajamas; (3) take a shower; (4) get dressed; (5) eat breakfast; (6) carpool to work. What could happen if the same steps are performed in a slightly different order; e.g., step (4) before step (3). Specifying the order in which statements (actions) execute in a program is called program control. Algorithms could be represented using Pseudocode (text representation) UML activity diagram (graphical representation) Education, Inc. All Rights Reserved. 2 1

2 Pseudocode is an informal language (similar to everyday English) that helps you develop algorithms without having to worry about the strict details of Java language syntax. It helps you think out a program before attempting to write it in a programming language, such as Java. Carefully prepared pseudocode can easily be converted to a corresponding Java program. Education, Inc. All Rights Reserved. 3 The UML (Unified Modeling Language) is a graphical language that allows people who build software systems to represent their objectoriented designs in an industry standard notation. Activity diagrams are part of the UML. It models the workflow (the activity) of a portion of a software system. Such workflows may include a portion of an algorithm, such as the sequence structure in Fig Although many programmers prefer pseudocode. Activity diagrams clearly show how control structures operate. Initial state Action (Activity) Transition Note Final state Education, Inc. All Rights Reserved. 4 2

3 Write an application that inputs from the user the radius of a circle as a real number and prints the circle s diameter, circumference and area using the floating-point value 3.14 for π. Use the following formulas (r is the radius): diameter = 2r circumference = 2πr area = πr 2 Education, Inc. All Rights Reserved. 5 Prompt the user to enter the value of the radius of the circle Read the value of the radius and store it Calculate the diameter of the circle and store it Calculate the circumference of the circle and store it Calculate the area of the circle and store it Print the calculated value of the diameter Print the calculated value of the circumference Print the calculated value of the area Education, Inc. All Rights Reserved. 6 3

5 Modify your code as follows: Use the predefined constant Math.PI for the value of π. It is more precise. Use the predefined method Math.pow for calculating the value of r 2. Do not store the results of each calculation in a variable. Rather, specify each calculation as the value that will be output in a System.out.printf statement, and print the results rounded to 2 decimal places. Education, Inc. All Rights Reserved. 9 import java.util.scanner; public class Circle2 { public static void main( String[] args ) { Scanner keyboard = new Scanner(System.in); double radius; System.out.print("Enter radius: "); // prompt radius = keyboard.nextdouble(); // read radius System.out.printf("Diameter is %.2f\n", (2 * radius)); System.out.printf("Circumference is %.2f\n", Try to remove the (2 * Math.PI * radius)); rounding and see System.out.printf("Area is %.2f\n", the result Math.PI * Math.pow(radius, 2)); } // end main method } // end class Circle output----- Enter radius: 6.2 Diameter is Circumference is Area is output without rounding--- Enter radius: 6.2 Diameter is Circumference is Area is Education, Inc. All Rights Reserved. 10 5

10 Sequential execution (Sequence structure): Unless directed otherwise, the computer executes Java statements one after the other in the order in which they are written, like all the programs we implemented till now. Transfer of control: Various Java statements, enable you to specify that the next statement to execute is not necessarily the next one in sequence. Education, Inc. All Rights Reserved. 19 Three types of selection statements. if statement: Performs an action, if a condition is true; skips it, if false. Single-selection statement selects or ignores a single action (or group of actions). if else statement: Performs an action if a condition is true and performs a different action if the condition is false. Double-selection statement selects between two different actions (or groups of actions). switch statement Performs one of several actions, based on the value of an expression. Multiple-selection statement selects among many different actions (or groups of actions). Education, Inc. All Rights Reserved

11 Three repetition statements (also called looping statements) Perform statements repeatedly while a loop-continuation condition remains true. while and for statements perform the action(s) in their bodies zero or more times if the loop-continuation condition is initially false, the body will not execute. The do while statement performs the action(s) in its body one or more times. if, else, switch, while, do and for are keywords. Appendix C: Complete list of Java keywords. Education, Inc. All Rights Reserved. 21 Every program is formed by combining the sequence statements, selection statements (three types) and repetition statements (three types) as appropriate for the algorithm the program implements. Bohm and Jacopini Demonstrated that programs could be written without any goto statements. All programs can be written in terms of only three control structures the sequence structure, the selection structure and the repetition structure. When we introduce Java s control structure implementations, we ll refer to them in the terminology of the Java Language Specification as control statements. Can model each control statement as an activity diagram. Education, Inc. All Rights Reserved

12 Condition: An expression that can be true or false. Education, Inc. All Rights Reserved. 23 Pseudocode If student s grade is greater than or equal to 60 Print Passed If the condition is false, the Print statement is ignored, and the next pseudocode statement in order is performed. Indentation Optional, but recommended Emphasizes the inherent structure of structured programs The preceding pseudocode if in Java: if (studentgrade >= 60) System.out.println("Passed"); The condition of if should be a boolean expression evaluates to a boolean value (true or false) Education, Inc. All Rights Reserved

13 Figure 4.2 if statement UML activity diagram. Each transition arrow emerging from a decision symbol (diamond) has a guard condition (in square brackets next to the arrow). If a guard condition is true, the workflow enters the action state to which the transition arrow points. Decision diamond Guard condition Education, Inc. All Rights Reserved. 25 if else double-selection statement specify an action to perform when the condition is true and a different action when the condition is false. Pseudocode If student s grade is greater than or equal to 60 Print Passed Else Print Failed The preceding if else pseudocode statement in Java: if (grade >= 60) System.out.println("Passed"); else System.out.println("Failed"); Note that the body of the else is also indented. Education, Inc. All Rights Reserved

14 Figure 4.3 illustrates the flow of control in the if else statement. Education, Inc. All Rights Reserved. 27 The if statement normally expects only one statement in its body. To include several statements in the body of an if (or the body of an else for an if else statement), enclose the statements in braces. Statements contained in a pair of braces form a block. A block can be placed anywhere that a single statement can be placed. The else part should come immediately after the body of an if statement. Example: if ( grade >= 60 ) { System.out.println("Passed"); System.out.println( Nice!"); } else { System.out.println("Failed"); System.out.println("You must take this course again."); } Education, Inc. All Rights Reserved

15 Conditional operator (?:) shorthand if else. Ternary operator (takes three operands) Operands and?: form a conditional expression Operand to the left of the? is a boolean expression. Second operand (between the? and :) is the value if the boolean expression is true Third operand (to the right of the :) is the value if the boolean expression evaluates to false. Example: System.out.println( studentgrade >= 60? "Passed" : "Failed" ); Evaluates to the string "Passed" if the boolean expression studentgrade >= 60 is true and to the string "Failed" if it is false. Education, Inc. All Rights Reserved. 29 Education, Inc. All Rights Reserved

Programming Languages: Java Lecture 1 Introduction to Java Instructor: Omer Boyaci 1 2 Course Information History of Java Introduction First Program in Java: Printing a Line of Text Modifying Our First

1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

switch Multiple-Selection Statement (This feature is rarely useful, although it s perfect for programming the iterative song The Twelve Days of Christmas!) If no match occurs, the default case is executed,

1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

T U T O R I A L 7 Objectives In this tutorial, you will learn to: Understand basic problemsolving techniques. Understand control structures. Understand and create pseudocode. Use the If Then and If Then

COUNTING LOOPS AND ACCUMULATORS Two very important looping idioms are counting loops and accumulators. A counting loop uses a variable, called the loop control variable, to keep count of how many cycles

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program,

Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

26 Chapter 3 Arithmetic Expressions Java programs can solve mathematical problems. Often programs that appear nonmathematical on the surface perform a large number of mathematical calculations behind the

Flow of Control CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 The order in which statements are executed

Control Statements: Part 2, Solutions 5 Let s all move one place on Lewis Carroll The wheel is come full circle William Shakespeare How many apples fell on Newton s head before he took the hint! Robert

THE JAVA API The Java API which stands for Application Programming Interface is a repository of prewritten classes provided by the creators of Java to enhance its usefulness. There are classes for creating

Adjusted/Modified by Nicole Tobias Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types

C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 4: Control Structures I (Selection) Objectives In this chapter, you will: Learn about control structures Examine relational

7 Introduction to C++ 7.1 Introduction C++ is an extension to C Programming language. It was developed at AT&T Bell Laboratories in the early 1980s by Bjarne Stroustrup. It is a deviation from traditional

CS1Ah Lecture Note 5 Java Expressions Many Java statements can contain expressions, which are program phrases that tell how to compute a data value. Expressions can involve arithmetic calculation and method

Lab 3: Operators In this lab, you will work with Java operators. Objectives: To learn Java operators Part 0: Getting Started Ask your instructor for the following information: Lab Installation directory:

PROGRAMMING REFRESHER MODULE Delivered by Ana Cavalcanti and Alvaro Miyazawa Prepared by Dr Lilian Blot The Rules Everything in PREF (Week 1) is optional. From week 2 of APRC and JAPC, we assume that all

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

14 Chapter 2 Values, Variables, and Types In this chapter we explore the primitive building blocks that are used to develop Java programs. We experiment with the following concepts within DrJava s interactive

Algorithm & Flowchart & Pseudo code Staff Incharge: S.Sasirekha Computer Programming and Languages Computers work on a set of instructions called computer program, which clearly specify the ways to carry

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

Chapter 4 Operators & Arithmetic 4-1 Arithmetic in C++ Arithmetic expressions can be made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition)

Java Review (Essentials of Java for Hadoop) Have You Joined Our LinkedIn Group? What is Java? Java JRE - Java is not just a programming language but it is a complete platform for object oriented programming.

Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

The Math Class It is hard to avoid the Math class in any Java program that requires scientific or other numeric computations. As with the wrapper classes, the Math class is part of the java.lang package;

Java: Primitive Data Types, Variables and Constants Introduction A primitive data type is a data type provided as a basic building block by a programming language. It is predefined by the programming language

CHAPTER 3 Program Elements Notes Chapter 3 introduces the program elements that are the underlying constructs used inside an object to define the services it contributes to a program. Without these constructs,

- 1 - GETTING STARTED WITH C++ Programming is a core activity in the process of performing tasks or solving problems with the aid of a computer. An idealised picture is: PROBLEM COMPUTER SOLUTION Unfortunately

Java Names and Variables GEEN163 Introduction to Computer Programming What s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare Clickers Clicking will be required

[Page 70 (continued)] Exercises 2.7 Discuss the meaning of each of the following objects: a. std::cin b. std::cout 2.8 Fill in the blanks in each of the following: a. are used to document a program and

Strings in Java are objects. They are instances of the class String (in the package java.lang). As is the case with other objects, String variables are actually references to a String object in memory.

Chapter 6. Transition to Java Not all programming languages are created equal. Each is designed by its creator to achieve a particular purpose, which can range from highly focused languages designed for

Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead

Unit-4 Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language. To understand expression evaluation, need to be familiar

Going from Python to C Darin Brezeale December 8, 2011 Python is a high-level, interpreted language. C has many of the same types of programming constructs as in Python: arrays, loops, conditionals, functions,

IRA EXAMPLES This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account). Definite Counting Loop Example IRA After x Years This first example illustrates

Introduction Borland C++ Compiler: Operators An operator is a symbol that specifies which operation to perform in a statement or expression. An operand is one of the inputs of an operator. For example,

PE1 Worksheet Problem solving 1) What are the four stages of problem solving by programming? What shall be done in each stage? Stage 1: Stage 2: Stage 3: Stage 4: 2) What is the top-down design strategy

Chapter 2: Elementary Programming CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations In the preceding chapter, you learned how to

Notes on Algorithms, Pseudocode, and Flowcharts Introduction Do you like hot sauce? Here is an algorithm for how to make a good one: Volcanic Hot Sauce (from: http://recipeland.com/recipe/v/volcanic-hot-sauce-1125)

Fundamentals of Programming Laboratory 5 Methods. General-purpose and user - defined methods What is a method? Block of code that receives its own identifier - i.e. can be executed using its name Different

Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

Chapter Four MULTIPLE CHOICE 1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. iteration 2. The decision structure

Unit 2: Libraries, Packages, Components, Types, and Variables Preview of Coming Attractions In this unit be sure to look for different types of libraries packages import command primitive types and component

Lecture 3 Using Classes and Objects Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and object references

AP Computer Science Static Methods, Strings, User Input Static Methods The Math class contains a special type of methods, called static methods. A static method DOES NOT operate on an object. This is because

Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of