Selection as a Control Structure
|
|
- Amice McGee
- 5 years ago
- Views:
Transcription
1 Java the UML Way version Selection as a Control Structure Control structures page 2 The Calculator class with a client program page 3-5 Blocks inside methods page 6 The if statement has two forms page 7 Curly braces and indents page 8 Nested if and multiple choice statements page 9-10 Decision tables page 11 Boolean expressions page Comparing strings page Short-circuit evaluation page 16 The switch statement page 17 Comparing computed decimal numerals page 18 Chapter 5
2 Control Structures An algorithm is a limited and ordered set of well-defined rules for solving a problem (see chapter 2) a given order Three categories of execution order or control structures: sequential (all client programs up to now) selection (the if statement, this chapter) loop (the while statement, see chapter 6) Activity diagrams illustrate control structures. Chapter 5, page 2
3 Class Diagram and Two Possible Activity Diagrams for a Calculator object read two numbers Calculator number1 number2 getnumber1 getnumber2 setnumbers calculatesum calculatedifference calculateproduct calculatequotient read two numbers Calculator calcus = new Calculator(number1, number2) calcus.calculatesum() print the result Calculator calcus = new Calculator(number1, number2) [will not add the numbers] calcus. calculatedifference() print the result [will add the numbers] calcus. calculatesum() Chapter 5, page 3
4 The Calculator Class class Calculator { private double number1; private double number2; public Calculator(double initnumber1, double initnumber2) { number1 = initnumber1; number2 = initnumber2; public double getnumber1() { return number1; public double getnumber2() { return number2; public void setnumbers(double newnumber1, double newnumber2) { number1 = newnumber1; number2 = newnumber2; public double calculatesum() { return number1 + number2; public double calculatedifference() { return number1 - number2; public double calculateproduct() { return number1 * number2; public double calculatequotient() { /* Division by zero gives special results: * Both numerator and denominator are 0: * Result: Double.NaN ("not-a-number") * Only denominator is 0: * Result: Double.NEGATIVE_INFINITY or * Double.POSITIVE_INFINITY. * Printing these values gives "NaN" and "Infinity". */ return number1 / number2; Chapter 5, page 4
5 Client Program with Selection the selection has to be formulated as a yes/no question import javax.swing.joptionpane; class TestCalculator1 { public static void main(string[] args) { /* Reading data */ String number1read = JOptionPane.showInputDialog("First number: "); String number2read = JOptionPane.showInputDialog("Second number: "); double number1 = Double.parseDouble(number1Read); double number2 = Double.parseDouble(number2Read); int answer = JOptionPane.showConfirmDialog(null, "Add the numbers? ", "Calculator", JOptionPane.YES_NO_OPTION); /* Calculating results */ Calculator calcus = new Calculator(number1, number2); double calculatedanswer; char operator; if (answer == JOptionPane.YES_OPTION) { // Yes is pressed calculatedanswer = calcus.calculatesum(); operator = '+'; else { // No or Esc is pressed, or the dialogue is closed calculatedanswer = calcus.calculatedifference(); operator = '-'; /* Printing results */ String result = "Our calculation: " + calcus.getnumber1() + " " + operator + " " + calcus.getnumber2(); result += "\nthe answer is " + calculatedanswer; JOptionPane.showMessageDialog(null, result); System.exit(0); Solve problem 2, page 125. Chapter 5, page 5
6 Blocks Inside Methods Local variables are variables declared inside methods. The scope of a local variable is the rest of the block where the variable is declared. A method may contain many blocks inside each other. Variables can be declared inside blocks. As a recommended practice, variables should be declared near the place they are used. An alternative calculator program is shown to the right. The scope of the variables is shown. Solve problem 2, pp number1 number2 calcus answer result calculatedanswer calculatedanswer public static void main(string[] args) {. double number1 = double number2 = Calculator calcus =. int answer = JOptionPane.. String result =.. if (answer == JOptionPane.YES_OPTION) { double calculatedanswer = calcus.calculatesum(); result += "+" + calcus.getnumber2() + "\nthe answer is " + calculatedanswer; else { double calculatedanswer = calcus.calculatedifference(); result += "-" + calcus.getnumber2() + "\nthe answer is " + calculatedanswer; JOptionPane.showMessageDialog(null, result); System.exit(0); Chapter 5, page 6
7 [not (boolean expression)] The if Statement has Two Versions [boolean expression] NB! Equality is written with two equality signs. if (boolean expression) statement1 else statement2 [not (boolean expression)] [boolean expression] if (boolean expression) statement A boolean expression may be a boolean variable or a comparision, examples: a > 10 noofgirls < noofboys noofmen == noofwomen Chapter 5, page 7
8 Curly Braces and Indents if (boolean expression) statement1 else statement2 If statement1 and/or statement2 consist of more than one individual statement, the statements have to be enclosed in curly braces {. Otherwise, it s not necessary to use curly braces. However, for the sake of readability, and to decrease the chance of errors, we also recommend using curly braces if only one individual statement is to be executed and there isn t room for it on the same line as if or else. Example, we have discovered that b should be increased by 1 if a > b: Starting point: Correction: if (a > b) if (a > b) sum += a; sum += a; b++; Why isn't this "correction" correct? Do you think the chance to get the code correct is higher if the starting point is as follows: if (a > b) sum += a; If so, why? Discussion / conclusion? Solve problem 2, page 136. Chapter 5, page 8
9 Nested if and Multiple-Choice Statements Example: if (temperature > 0) { System.out.println( "Degrees above zero."); if (temperature == 0) { System.out.println("Zero degrees."); if (temperature < 0) { System.out.println("Degrees below zero."); A few superfluous tests. Superfluous tests are removed: if (temperature > 0) { System.out.println("Degrees above zero."); else { if (temperature == 0) { System.out.println("Zero degrees."); else { System.out.println("Degrees below zero."); // end of the innermost if-else statement // end of the outermost if-else statement Or we could write: if (temperature > 0) System.out.println("Degrees above zero."); else if (temperature == 0) System.out.println("Zero degrees"); else System.out.println("Degrees below zero."); Chapter 5, page 9
10 What's the Difference between the Following Two Code Segments? int a = -10; int b = 20; if (a > 0) { if (b > 10) b = 10; else a = 0; System.out.println(a + " " + b); a = -10; b = 20; if (a > 0) if (b > 10) b = 10; else a = 0; System.out.println(a + " " + b); If you use multiple if statements inside each other (nested if), and an else block doesn t belong to the closest preceding if, it has to be marked with {. Solve problem 2, page 144. Chapter 5, page 10
11 Decision Tables A grade is computed according to the following decision table: points grade A B C D 0-59 F Problem: Complete the getgrade() method: class Grade { private int points; public Grade(int initpoints) { points = initpoints; public int getgrade() { // negative value is returned if invalid no. of points. fill inn what is missing... Chapter 5, page 11
12 Boolean Expressions A boolean expression has the value true or false. The logical-complement operator! (also called the not-operator) reverses the expression s value.!true is false and vice versa. Boolean expressions are created using the comparison operators: < less than <= less than or equal to Examples: > greater than number > 10 >= greater than or equal to (price * number)!= 100!= not equal to number1 + number2 == number3 + number4 ==equal to More complex expressions are created combining simple boolean expressions using the following two operators: && conditional-and (or only: and ) conditional-or (or only: or ) See operator summary, table 5.4, page 147. Chapter 5, page 12
13 Calculating a Complex Boolean Expression a >= 0 && a <= 4 a >= 10 && a <= 15 a == 20 a is equal to 16 true false true false false false false false false Solve all problems, pp Chapter 5, page 13
14 Comparing Strings The String class offers methods to comparing strings. Two strings are given: String name1 = "Margaret Eliza"; String name2 = "Maya"; Using the equals() method: if (name1.equals(name2)) System.out.println("The names are the same."); else System.out.println("The names are not the same."); Printout: The names are not the same. Using the compareto() method: int result = name1.compareto(name2); if (result < 0) System.out.println(name1 + " comes first."); else if (result > 0) System.out.println(name2 + " comes first."); else System.out.println("The names are the same."); Printout: Margaret Eliza comes first. Chapter 5, page 14
15 Methods for Comparing Strings The String class offers the following methods for comparing strings: public int compareto(string theotherstring) public boolean equals(object theotherobject) public boolean equalsignorecase(string theotherstring) public int comparetoignorecase(string theotherstring) Comparing is according to the Unicode order. The compareto() methods returns a negative value if the string we re sending the message to comes before theotherstring in the order, a positive value if it comes after, and 0 if the strings are equal. Chapter 5, page 15
16 Short-Circuit Evaluation Boolean expressions containing the operators && or are calculated using short-circuit evaluation. The computation is ended as soon as the result is determined. If we have an && ( and ) operator between the expressions: Continue the evaluation as long as the expressions are true. The instant the Java interpreter encounters the first expression which evaluates to false, the compound expression as a whole will be false, and it can terminate the computation. If we have an ( or ) operator between the expressions: Continue the evaluation as long as the expressions are false. The instant one of them is true, the Java interpreter can stop, because then the whole expression is true. An example: if (number >= 0 && Math.sqrt(number) < limit)... In this example, the order of the comparisons cannot be swapped. If we do so, we risk trying to compute the square root of a negative number. Chapter 5, page 16
17 The switch Statement If each instance in a multiplechoice statement corresponds to a specific numerical value or a character, it may be practical to use the switch statement. See example to the right. All the labels have to represent different constant expressions in other words, separate values. Thus, it s not possible to provide an interval or a list of values here. Jump out of the switch block only through "break". Solve problem, page 152. String text = JOptionPane.showInputDialog("Which place? "); int place = Integer.parseInt(text); switch (place) { case 1: JOptionPane.showMessageDialog(null, "Gold!"); break; case 2: JOptionPane.showMessageDialog(null, "Silver!"); break; case 3: JOptionPane.showMessageDialog(null, "Bronze!"); break; case 4: /* falls through */ case 5: /* falls through */ case 6: JOptionPane.showMessageDialog(null, "You have points!"); break; default: int luckynumber = (int) (100 * Math.random() + 1); JOptionPane.showMessageDialog(null, "Thank you for honourable achievement!\n" + "Your lucky number is: " + luckynumber); break; Chapter 5, page 17
18 Comparing Computed Decimal Numerals What is the value of number3 after the following code segment is executed: double number1 = 1.0e20; double number2 = number ; double number3 = number2 - number1; Answer: number3 is 0. Why? 1 + 1, = 1, The double data type handles only approx. 15 significant digits. The value 1 is loosed if we try to add it to the very large number. Never use the operators == and!= to compare results from calculations involving decimal numerals. Instead, check that the difference between the numbers is less than a given tolerance (the size of the tolerance should be according to the numbers): final double tolerance = ; if (Math.abs(number1 - number2) < tolerance) { System.out.println("The numbers are almost the same."); else System.out.println("The numbers are different."); remember using the absolute value! Chapter 5, page 18
Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures
Chapter 4: Control Structures I Java Programming: Program Design Including Data Structures Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form
More informationAPCS Semester #1 Final Exam Practice Problems
Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester
More informationTopics. Chapter 5. Equality Operators
Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements Outline Problem: How do I make choices in my Java program? Understanding conditional statements Remember: Boolean logic
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements Outline Problem: How do I make choices in my Java program? Understanding conditional statements Remember: Boolean logic
More informationIn Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.
CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in
More informationLanguage Fundamentals Summary
Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de
More informationConditionals and Loops
Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional
More informationFlow of Control. Chapter 3. Chapter 3 1
Flow of Control Chapter 3 Chapter 3 1 Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement chooses between
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More informationSOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)
SOFTWARE DEVELOPMENT 1 Control Structures 2018W (Institute of Pervasive Computing, JKU Linz) WHAT IS CONTROL FLOW? The control flow determines the order in which instructions are executed. Default: from
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures Agenda 1. Block Statements 2. Decision Statements 3. Loops 2 What are Control
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 05 / 31 / 2017 Instructor: Michael Eckmann Today s Topics Questions / Comments? recap and some more details about variables, and if / else statements do lab work
More informationChapter 4: Control Structures I
Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore
More informationFlow of Control. Chapter 3
Flow of Control Chapter 3 The Conditional Operator if (n1 > n2) else max = n1; max = n2; can be written as max = (n1 > n2)? n1 : n2; The? and : together are call the conditional operator or ternary operator.
More informationCMPT 125: Lecture 4 Conditionals and Loops
CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed
More informationComputer Programming, I. Laboratory Manual. Experiment #3. Selections
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 #3
More informationLab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.
Lab 8: IF statement. Conditionals and Loops The if condition Statement A conditional statement lets us choose which statement will be executed next if is a Java reserved word The condition must be a boolean
More informationJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
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
More informationCCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives
LIANMC03v3_0132221586.QXD 5/15/06 7:41 PM Page 67 CCHAPTER HAPTER 3 1 SELECTION STATEMENTS Objectives To declare boolean type and write Boolean expressions ( 3.2). To distinguish between conditional and
More informationChapter 3 Selection Statements
Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are
More informationFollowing is the general form of a typical decision making structure found in most of the programming languages:
Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined
More informationEng. Mohammed S. Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 3 Selections
More informationIn this chapter, you will:
Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an
More informationControl Structures. Lecture 4 COP 3014 Fall September 18, 2017
Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls
More informationConditions, logical expressions, and selection. Introduction to control structures
Conditions, logical expressions, and selection Introduction to control structures Flow of control In a program, statements execute in a particular order By default, statements are executed sequentially:
More informationVariables and data types
Survivor: CSCI 135 Variables Variables and data types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations String
More informationExpressions and Data Types CSC 121 Spring 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types
More informationCS1004: Intro to CS in Java, Spring 2005
CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What
More informationCONDITIONAL EXECUTION
CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons
More informationWhat methods does the String class provide for ignoring case sensitive situations?
Nov. 20 What methods does the String class provide for ignoring case sensitive situations? What is a local variable? What is the span of a local variable? How many operands does a conditional operator
More informationFlow of Control. Flow of control The order in which statements are executed. Transfer of control
1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control
More informationV2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed
Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control
More informationChapter 3: Decision Structures
Chapter 3: Decision Structures Chapter Topics Chapter 3 discusses the following main topics: The if Statement The if-else Statement Nested if statements The if-else-if Statement Logical Operators Comparing
More informationSequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;
Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More information1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'
Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java
More informationChapter 3: Decision Structures
Chapter 3: Decision Structures Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All rights reserved.
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationChapter 3: Decision Structures
Chapter 3: Decision Structures Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 3 discusses the following main topics: The if Statement
More informationComputational Expression
Computational Expression Conditionals Janyl Jumadinova 10 October, 2018 Janyl Jumadinova Computational Expression 10 October, 2018 1 / 16 Computational Thinking: a problem solving process Decomposition
More informationMidterm 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 informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More information3chapter C ONTROL S TATEMENTS. Objectives
3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (
More informationZheng-Liang Lu Java Programming 45 / 79
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius
More informationUniversity of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb 9 2006 based on slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/cpsc111-06-spr
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
More informationJAVA OPERATORS GENERAL
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
More informationChapter 2: Using Data
Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that
More informationControl Structures in Java if-else and switch
Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification
More informationMore about JOptionPane Dialog Boxes
APPENDIX K More about JOptionPane Dialog Boxes In Chapter 2 you learned how to use the JOptionPane class to display message dialog boxes and input dialog boxes. This appendix provides a more detailed discussion
More informationChapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius
More informationOverview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University
Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the
More informationKey Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent
Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information
More informationCOMPUTER PROGRAMMING LOOPS
COMPUTER PROGRAMMING LOOPS http://www.tutorialspoint.com/computer_programming/computer_programming_loops.htm Copyright tutorialspoint.com Let's consider a situation when you want to write five times. Here
More informationExpressions and Data Types CSC 121 Fall 2015 Howard Rosenthal
Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and
More informationCSE 142 Su 04 Computer Programming 1 - Java. Objects
Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request
More informationJava Programming for Selenium
Video 5 - Java Control Flow, String Handling and Arrays Java Programming for Selenium 1) Conditional / Decision Making 2) Loop 3) Branching 4) String Handling in Java 5) Java Arrays 1) Conditional / Decision
More informationChapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.
Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)
More informationLecture 5 Tao Wang 1
Lecture 5 Tao Wang 1 Objectives In this chapter, you will learn about: Selection criteria Relational operators Logical operators The if-else statement Nested if statements C++ for Engineers and Scientists,
More informationIntroduction 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 informationOutline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.
OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce
More informationDM503 Programming B. Peter Schneider-Kamp.
DM503 Programming B Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm503/! VARIABLES, EXPRESSIONS & STATEMENTS 2 Values and Types Values = basic data objects 42 23.0 "Hello!" Types
More informationObject Oriented Programming with Java
Object Oriented Programming with Java What is Object Oriented Programming? Object Oriented Programming consists of creating outline structures that are easily reused over and over again. There are four
More informationb. Suppose you enter input from the console, when you run the program. What is the output?
Part I. Show the printout of the following code: (write the printout next to each println statement if the println statement is executed in the program). a. Show the output of the following code: public
More informationIntroduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017
Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor
More informationChapter 02: Using Data
True / False 1. A variable can hold more than one value at a time. ANSWER: False REFERENCES: 54 2. The int data type is the most commonly used integer type. ANSWER: True REFERENCES: 64 3. Multiplication,
More informationJava Programming Basics. COMP 401, Fall 2017 Lecture 2
Java Programming Basics COMP 401, Fall 2017 Lecture 2 A Java Program Line number where first loop starts * line number where an array is indexed + number of Jmes line 6 will execute total number of local
More informationThe Java language has a wide variety of modifiers, including the following:
PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 01 / 23 / 2015 Instructor: Michael Eckmann Today s Topics Questions? Comments? Review variables variable declaration assignment (changing a variable's value) using
More informationCS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University
CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java expressions and operators concluded Java Statements: Conditionals: if/then, if/then/else Loops: while, for Next
More informationConditionals, Loops, and Style
Conditionals, Loops, and Style yes x > y? no max = x; max = y; http://xkcd.com/292/ Fundamentals of Computer Science Keith Vertanen Copyright 2013 Control flow thus far public class ArgsExample public
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationControl Structures in Java if-else and switch
Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2016 February 2, 2016 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions
More informationCOMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon
More informationConditional Execution
Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {
More informationJava Flow of Control
Java Flow of Control SEEM 3460 1 Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationCT 229 Fundamentals of Java Syntax
CT 229 Fundamentals of Java Syntax 19/09/2006 CT229 New Lab Assignment Monday 18 th Sept -> New Lab Assignment on CT 229 Website Two Weeks for Completion Due Date is Oct 1 st Assignment Submission is online
More informationOct Decision Structures cont d
Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements
More informationComparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD
1 CS257 Computer Science I Kevin Sahr, PhD Lecture 6: Comparing Data and Complex Boolean Expressions Comparing Data 2 When comparing data it's important to understand the nuances of certain data types
More informationModule 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1
Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often
More informationReview 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 informationProblem 7.4: Racetrack
ENCE 688R: Solutions to Homework 1 March 2016 Problem 7.3: Find smallest number that is evenly divisible by all of the numbers 1 through 20. Source code: / =====================================================================
More informationCS1150 Principles of Computer Science Loops (Part II)
CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?
More informationFlow of Control. Chapter 3
Flow of Control Chapter 3 Outline The if-else Stetement The Type boolean The switch statement Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order
More informationJava Programming Basics. COMP 401, Spring 2017 Lecture 2
Java Programming Basics COMP 401, Spring 2017 Lecture 2 AverageHeightApp take 2 Same as before, but with Eclipse. Eclipse Workspace CreaJng new project CreaJng a new package CreaJng new class Running a
More informationChapter 4 - Notes Control Structures I (Selection)
Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by
More informationLogical Operators and switch
Lecture 5 Relational and Equivalence Operators SYS-1S22 / MTH-1A66 Logical Operators and switch Stuart Gibson sg@sys.uea.ac.uk S01.09A 1 Relational Operator Meaning < Less than > Greater than
More informationM e t h o d s a n d P a r a m e t e r s
M e t h o d s a n d P a r a m e t e r s Objective #1: Call methods. Methods are reusable sections of code that perform actions. Many methods come from classes that are built into the Java language. For
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationFaculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination November 7th, 2012 Examiners: Daniel Pomerantz [Sections
More informationChapter 3: Operators, Expressions and Type Conversion
101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To
More informationMotivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool
Chapter 3: Selections and Conditionals CS1: Java Programming Colorado State University Motivations If you assigned a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program
More informationObjectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators
Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)
More informationLecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan
Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCT 229 Java Syntax Continued
CT 229 Java Syntax Continued 29/09/2006 CT229 Lab Assignments One Week Extension for Lab Assignment 1. Due Date: Oct 8 th Before submission make sure that the name of each.java file matches the name given
More information