Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Similar documents
Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

switch-case Statements

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Arithmetic Compound Assignment Operators

++x vs. x++ We will use these notations very often.

Arithmetic Compound Assignment Operators

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example: Monte Carlo Simulation 1

Values in 2 s Complement

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

IEEE Floating-Point Representation 1

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CompSci 125 Lecture 11

More on control structures

Repetition, Looping. While Loop

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Exercise (Revisited)

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Loops and Expression Types

Problem Solving With Loops

Computer Programming I - Unit 5 Lecture page 1 of 14

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Assignment 2.4: Loops

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Building Java Programs

ECE 122. Engineering Problem Solving with Java

St. Edmund Preparatory High School Brooklyn, NY

Introduction to Java & Fundamental Data Types

Control Structures in Java if-else and switch

REPETITION CONTROL STRUCTURE LOGO

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Chapter 4 Introduction to Control Statements

STUDENT LESSON A12 Iterations

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Accelerating Information Technology Innovation

Introduction to Java Applications

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Controls Structure for Repetition

Introduction. C provides two styles of flow control:

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

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

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Flow of Control. Chapter 3 Part 3 The Switch Statement

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Iteration statements - Loops

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Lecture 3 Tao Wang 1

Loops. CSE 114, Computer Science 1 Stony Brook University

Control Structures in Java if-else and switch

Repetition Structures

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

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

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

AP Programming - Chapter 6 Lecture

Object-Oriented Programming

Programming with Java

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Course Outline. Introduction to java

CS110: PROGRAMMING LANGUAGE I

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Eng. Mohammed S. Abdualal

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

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Unit 1 Lesson 4. Introduction to Control Statements

n Group of statements that are executed repeatedly while some condition remains true

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Chapter 3: Operators, Expressions and Type Conversion

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

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

CSCI 1103: File I/O, Scanner, PrintWriter

Object-oriented programming in...

3 The L oop Control Structure

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CS111: PROGRAMMING LANGUAGE II

Condi(onals and Loops

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 8. Statement-Level Control Structures

Elementary Programming

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

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

Transcription:

Generating random numbers Example Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then the program reports Correct. and terminates. Otherwise, the program reports Wrong answer. The correct answer is 7. for this case. You may use Math.random() for a random value between 0.0 and 1.0, excluding themselves. 1 1 You may see PRNG in https://en.wikipedia.org/wiki/pseudorandom_number_generator. Zheng-Liang Lu Java Programming 102 / 134

2 int x = (int) (Math.random() 10); // integers 0 9 3 int y = (int) (Math.random() 10); 4 int answer = x + y; 5 6 System.out.println(x + " + " + y + " =?"); 7 8 Scanner input = new Scanner(System.in); 9 int z = input.nextint(); 10 11 if (z == answer) 12 System.out.println("Correct."); 13 else 14 System.out.println("Wrong. Answer: " + answer); 15 input.close(); 16... Can you extend this program for all arithmetic expressions (i.e., + )? Zheng-Liang Lu Java Programming 103 / 134

Exploring the unknown requires tolerating uncertainty. Brian Greene I can live with doubt, and uncertainty, and not knowing. I think it is much more interesting to live not knowing than have answers which might be wrong. Richard Feynman Zheng-Liang Lu Java Programming 104 / 134

Exercise Find Max Write a program which determines the maximum value in 3 random integers whose range from 0 to 99. How many variables do we need? How to compare? How to keep the maximum value? Zheng-Liang Lu Java Programming 105 / 134

2 int x = (int) (Math.random() 100); 3 int y = (int) (Math.random() 100); 4 int z = (int) (Math.random() 100); 5 6 int max = x; 7 if (y > max) max = y; 8 if (z > max) max = z; 9 System.out.println("max = " + max); 10... In this case, a scalar variable is not convenient. (Why?) So we need arrays and loops. Zheng-Liang Lu Java Programming 106 / 134

switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break; 12 default: 13 // statements 14 } 15... Zheng-Liang Lu Java Programming 107 / 134

A switch-case statement is more convenient than an if statement for multiple discrete conditions. The variable target, always enclosed in parentheses, must yield a value of char, byte, short, int, or String type. The value v 1,..., and v k must have the same data type as the variable target. In each case, a break statement is a must. 2 break is used to break a construct! The default case, which is optional, can be used to perform actions when none of the specified cases matches target. Counterpart to else statements. 2 If not, there will be a fall-through behavior. Zheng-Liang Lu Java Programming 108 / 134

Example 2 // RED: 0 3 // YELLOW: 1 4 // GREEN: 2 5 int trafficlight = (int) (Math.random() 3); 6 switch (trafficlight) { 7 case 0: 8 System.out.println("Stop!!!"); 9 break; 10 case 1: 11 System.out.println("Slow down!!"); 12 break; 13 case 2: 14 System.out.println("Go!"); 15 } 16... Zheng-Liang Lu Java Programming 109 / 134

Conditional Operators A conditional expression evaluates an expression based on the specified condition and returns a value accordingly. 2 somevar = booleanexpr? expra : exprb; 3... This is the only ternary operator in Java. If the boolean expression is evaluated true, then return expr A; otherwise, expr B. Zheng-Liang Lu Java Programming 110 / 134

For example, 2 if (num1 > num2) 3 max = num1; 4 else 5 max = num2; 6... Alternatively, one can use a conditional expression like this: 2 max = (num1 > num2)? num1 : num2; 3... Zheng-Liang Lu Java Programming 111 / 134

1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 // keywords: 8 while, do, for, break, continue Zheng-Liang Lu Java Programming 112 / 134

Loops A loop can be used to make a program execute statements repeatedly without having to code the same statements. For example, a program outputs Hello, Java. for 100 times. 2 System.out.println("Hello, Java."); 3 System.out.println("Hello, Java."); 4. 5. // copy and paste for 100 times 6. 7 System.out.println("Hello, Java."); 8... Zheng-Liang Lu Java Programming 113 / 134

2 int cnt = 0; 3 while (cnt < 100) { 4 System.out.println("Hello, Java."); 5 cnt++; 6 } 7... This is a simple example to show the power of loops. In practice, any routine which repeats couples of times 3 can be done by folding them into a loop. 3 I prefer to call them patterns. Zheng-Liang Lu Java Programming 114 / 134

成也迴圈, 敗也迴圈 Loops provide substantial computational power. Loops bring an efficient way of programming. Loops could consume a lot of time. 4 4 We will visit the analysis of algorithms in the end of this lecture. Zheng-Liang Lu Java Programming 115 / 134

while Loops A while loop executes statements repeatedly while the condition is true. 2 while (condition) { 3 // loop body 4 } 5... The condition should be a boolean expression which determines whether or not the execution of the body occurs. If true, the loop body is executed and check the condition again. Otherwise, the entire loop terminates. Zheng-Liang Lu Java Programming 116 / 134

Zheng-Liang Lu Java Programming 117 / 134

Example Write a program which sums up all integers from 1 to 100. In math, the question can be written as: sum = 1 + 2 + + 100. But this form is not doable in the machine. 5 5 We need to develop computational thinking. Read http://rsta.royalsocietypublishing.org/content/366/1881/3717.full or http://blog.orangeapple.tw/posts/what-is-computational-thinking/. Zheng-Liang Lu Java Programming 118 / 134

Normally, the machine executes the instructions sequentially. So one needs to decompose the math equation into several steps, like: 2 int sum = 0; 3 sum = sum + 1; 4 sum = sum + 2; 5. 6. 7. 8 sum = sum + 100; 9... It is obvious that many similar statements can be found. Zheng-Liang Lu Java Programming 119 / 134

Using a while loop, the program can be rearranged as follows: 2 int sum = 0; 3 int i = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... You should guarantee that the loop will terminate as expected. In practice, the number of loop steps (iterations) is unknown until the input data is given. Zheng-Liang Lu Java Programming 120 / 134

Malfunctioned Loops It is really easy to make an infinite loop. 2 while (true); 3... The common errors of the loops are: never start never stop not complete exceed the expected number of iterations Zheng-Liang Lu Java Programming 121 / 134

Example Write a program which asks the sum of two random integers and lets the user repeatedly enter a new answer until correct. 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random() 10); 4 int y = (int) (Math.random() 10); 5 int ans = x + y; 6 7 System.out.println(x + " + " + y + " =? "); 8 int z = input.nextint(); 9 10 while (z!= ans) { 11 System.out.println("Try again? "); 12 z = input.nextint(); 13 } 14 System.out.println("Correct."); 15 input.close(); 16... Zheng-Liang Lu Java Programming 122 / 134

Loop Design Strategy Writing a correct loop is not an easy task for novice programmers. Consider 3 steps when writing a loop: Find the pattern: identify the statements that need to be repeated. Wrap by loops: put these statements in the loop. Set the continuation condition: translate the criterion from the real world problem into computational conditions. 6 6 Not unique. Zheng-Liang Lu Java Programming 123 / 134

Sentinel-Controlled Loops Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop. For example, the operating systems and the GUI apps. Zheng-Liang Lu Java Programming 124 / 134

Example: Cashier Problem Write a program which sums over positive integers from consecutive inputs and then outputs the sum when the input is nonpositive. 2 int total = 0, price = 0; 3 Scanner input = new Scanner(System.in); 4 5 System.out.println("Enter price?"); 6 price = input.nextint(); 7 while (price > 0) { 8 total += price; 9 System.out.println("Enter price?"); 10 price = input.nextint(); 11 // These two lines above repeat Line 5 and 6?! 12 } 13 14 System.out.println("Total = " + total); 15 input.close(); 16... Zheng-Liang Lu Java Programming 125 / 134

do-while Loops A do-while loop is similar to a while loop except that it does execute the loop body first and then checks the loop continuation condition. 2 do { 3 // loop body 4 } while (condition); // Do not miss the semicolon! 5... Note that there is a semicolon at the end of the do-while loop. The do-while loops are also called posttest loops, in contrast to while loops, which are pretest loops. Zheng-Liang Lu Java Programming 126 / 134

Zheng-Liang Lu Java Programming 127 / 134

Example (Revisted) Write a program which sums over positive integers from consecutive inputs and then outputs the sum when the input is nonpositive. 2 int total = 0, price = 0; 3 Scanner input = new Scanner(System.in); 4 5 do { 6 total += price; 7 System.out.println("Enter price?"); 8 price = input.nextint(); 9 } while (price > 0); 10 11 System.out.println("Total = " + total); 12 input.close(); 13... Zheng-Liang Lu Java Programming 128 / 134

for Loops A for loop generally uses a variable to control how many times the loop body is executed. 2 for (init action; condition; increment) { 3 // loop body 4 } 5... init-action: declare and initialize a variable condition: set a criterion for loop continuation increment: how the variable changes after each iteration Note that these terms are separated by semicolons. Zheng-Liang Lu Java Programming 129 / 134

Sum from 1 to 100 Example Write a program which sums from 1 to 100. 2 int sum = 0; 3 for (int i = 1; i <= 100; ++i) 4 sum = sum + i; 5... Compared to the while version, 2 int sum = 0; 3 int i = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... Zheng-Liang Lu Java Programming 130 / 134

Zheng-Liang Lu Java Programming 131 / 134

Example: Selection Resided in Loop Display all even numbers Write a program which displays all even numbers smaller than 100. An even number is an integer of the form x = 2k, where k is an integer. Zheng-Liang Lu Java Programming 132 / 134

You may use the modular operator (%). 2 for (int i = 1; i <= 100; i++) { 3 if (i % 2 == 0) System.out.println(i); 4 } 5... Also consider this alternative: 2 for (int i = 2; i <= 100; i += 2) { 3 System.out.println(i); 4 } 5... How about odd numbers? Zheng-Liang Lu Java Programming 133 / 134

Example: Monte Carlo Simulation 7 Write a program which conducts a Monte Carlo simulation to estimate π. 7 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 134 / 134