Values in 2 s Complement

Similar documents
Zheng-Liang Lu Java Programming 45 / 79

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

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

Arithmetic Compound Assignment Operators

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

IEEE Floating-Point Representation 1

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

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

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

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

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.

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

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

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

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

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

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

Arithmetic Compound Assignment Operators

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

switch-case Statements

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

Eng. Mohammed S. Abdualal

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

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

Example: Monte Carlo Simulation 1

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

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

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

Chapter 2 ELEMENTARY PROGRAMMING

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CEN 414 Java Programming

Full file at

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Chapter 2 Elementary Programming

Programming with Java

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

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

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

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

Chapter 3: Operators, Expressions and Type Conversion

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Chapter 3 Selection Statements

Exercise (Revisited)

Java Programming Language. 0 A history

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 3. Selections

These are reserved words of the C language. For example int, float, if, else, for, while etc.

JAVA OPERATORS GENERAL

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

Pace University. Fundamental Concepts of CS121 1

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Date: Dr. Essam Halim

COMP 202 Java in one week

Chapter 2. Elementary Programming

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

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

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

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Chapter 4 Introduction to Control Statements

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

JAVA Programming Fundamentals

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

What did we talk about last time? Examples switch statements

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2: Data and Expressions

Course Outline. Introduction to java

Introduction to Java Applications

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP 202. Java in one week

CS111: PROGRAMMING LANGUAGE II

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

Chapter 2: Data and Expressions

Important Java terminology

Oct Decision Structures cont d

Computer System and programming in C

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Full file at

More Programming Constructs -- Introduction

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Repetition, Looping. While Loop

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

3 The L oop Control Structure

Unit 1 Lesson 4. Introduction to Control Statements

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

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

Program Control Flow

Program Control Flow

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Transcription:

Values in 2 s Complement Java uses an encoding known as 2 s complement 1, which means that negative numbers are represented by inverting 2 all of the bits in a value, then adding 1 to the result. For example, 42 10 = 00101010 2. Then 42 10 = 11010110 2 can be derived from inverting 42 10 to 11010101 2 plus 1. 1 In 1 s complement, simply inverting all of the bits creates 11111111, which creates negative zero. The trouble is that negative zero is invalid in integer math. 2 Changing 1 s to 0 s and vice versa. Zheng-Liang Lu Java Programming 50 / 146

Identifiers Identifiers are the names that identify the elements such as variables, methods, and classes in a program. All identifiers must obey the following rules: a sequence of characters that consists of letters, digits, and underscores ( ) start with a letter or an underscore ( ) can be of any length cannot start with a digit cannot be a reserved word cannot be true, false, or null cannot contain +,,, and % Note that Java is case sensitive 3. 3 The letters A and a are different. Zheng-Liang Lu Java Programming 51 / 146

Reserved Words 4 4 See Appendix A in YDL, p. 1253. Zheng-Liang Lu Java Programming 52 / 146

When To Declare Variables: Two Before Rules Every variable has a scope. The scope of a variable is the part of the program where the variable can be referenced. A variable must be declared before it can be assigned a value. A declared variable must be assigned a value before it can be used. 5 The detail of variable scope is introduced later. 5 In symbolic programming, such as Mathematica and Maple, a variable can be manipulated without assigning a value. Zheng-Liang Lu Java Programming 53 / 146

Data Types Java is a strongly typed programming language. Every variable has a type. Every expression has a type. Every type is strictly defined. All assignments are checked for type compatibility. 6 There are two categories of date types: primitive data types, referential data types. 6 By Java compiler. Zheng-Liang Lu Java Programming 54 / 146

Primitive Data Types 7 7 See Figure 3-4 in Sharan, p. 67. Zheng-Liang Lu Java Programming 55 / 146

Integers The most commonly used integer type is int. long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. Note that when byte and short values are used in an expression, they are promoted to int when the expression is evaluated. 8 8 Due to the first bullet. Zheng-Liang Lu Java Programming 56 / 146

Floating Points Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. All transcendental math functions, such as sin(), cos(), and sqrt(), return double values. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. Be aware that floating-point arithmetic can only approximate real arithmetic. (Why?) Zheng-Liang Lu Java Programming 57 / 146

Example: 0.5-0.1-0.1-0.1-0.1-0.1 = 0? 1 public class displaytime { 2 public static void main(string args[]) { 3 System.out.println(0.5 0.1 0.1 0.1 0.1 0.1); 4 } 5 } The result is surprising. Why? Decimal-binary converter Zheng-Liang Lu Java Programming 58 / 146

IEEE Floating-Point Representation 9 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either between 1 and 2 ɛ, or between 0 and 1 ɛ. The exponent E weights the value by a (possibly negative) power of 2. 9 William Kahan (1985) Zheng-Liang Lu Java Programming 59 / 146

Illustration 10 10 See Figure 2-31 in Byrant, p. 104. Zheng-Liang Lu Java Programming 60 / 146

Assginment Statement An assignment statement designates a value for a variable, by the following syntax: 1... 2 myvar = expression; 3... The equal sign (=) is used as the assignment operator. For example, is the expression x = x + 1 correct? From the right-hand side to the left-hand side An expression represents a computation involving values, variables, and operators that evaluates to a value. To assign a value to a variable, you must place the variable name to the left of the assignment operator. 11 For example, 1 = x is wrong. 11 x can be a L-value and R-value, but 1 and other numbers can be only r-value but not l-value. See Value. Zheng-Liang Lu Java Programming 61 / 146

Variable Initialization Initialization once declaration 1... 2 int x = 1, y = 2; // Equivalent to int x, y; x = 1; y = 2; 3... Dynamical initialization 1... 2 double x, y = 3.0; 3 x = y; 4... y is assigned in the compilation stage; x is assigned in the runtime stage. Zheng-Liang Lu Java Programming 62 / 146

Numeric Operators 12 Note that when both operands of a division are integers, the result of the division is an integer and the fractional part is truncated. So, the operator depends on the operands. 12 See Table 2-3 in YDL, p. 46. Zheng-Liang Lu Java Programming 63 / 146

Example 1... 2 int a, b; 3 double c,d; 4 a = c = b = d = 3 + 7 / 2.; 5... a =? b =? c =? d =? Zheng-Liang Lu Java Programming 64 / 146

Type Conversion If the two types are compatible, then Java will perform the conversion automatically. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. The two types are compatible. The destination type is larger than the source type. For example, there is no automatic conversion defined from double to byte. (Why?) To do so, you must use a cast, which performs an explicit conversion between incompatible types. Zheng-Liang Lu Java Programming 65 / 146

Casting 1 public class test { 2 public static void main (String[] args) { 3 double x = 1.234; 4 int y; 5 y = (int) x; // (target type) 6 System.out.println("y = " + y); 7 } 8 } Target-type specifies the desired type to convert the specified value to. In this example, a different type of conversion will occur when a floating-point value is assigned to an integer type, as known as, truncation. Zheng-Liang Lu Java Programming 66 / 146

Example 1 public class promote { 2 public static void main(string[] args) { 3 byte b = 42; 4 char c = a ; // single quote for a letter, a > 97 5 short s = 1024; 6 int i = 50000; 7 float f = 5.67; 8 double d =.1234; 9 double result = (f b) + (i / c) (d s); 0 System.out.println((f b) + " + " + (i / c) + " " + 1 (d s) + " = " + result); 2 } 3 } (i/c) =? How to correct? Zheng-Liang Lu Java Programming 67 / 146

Type Promotion (Concluded) Type promotion rules are as follows: All byte, short, and char values are promoted to int. If one operand is a long, the whole expression is promoted to long. Similarly, if one is float, then promoted to float. Also, if any of the operands are double, then promoted to double. Zheng-Liang Lu Java Programming 68 / 146

Characters A character is stored in a computer as a sequence of 0s and 1s. The char data type is a 16-bit unsigned Java primitive data type. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. Zheng-Liang Lu Java Programming 69 / 146

ASCII (7-bit version) Zheng-Liang Lu Java Programming 70 / 146

Example Characters can also be used as an integer type on which you can perform arithmetic operations. For example, 1... 2 char x = a ; // Cannot be "a" 3 System.out.println(x + 1); 4 System.out.println((char)(x + 1)); 5 System.out.println(x + "1"); 6 System.out.println("This is " + x + 1); 7 System.out.println("This is " + (x + 1)); 8... x =? Note that the plus (+) operator is overloaded. Zheng-Liang Lu Java Programming 71 / 146

Character Escape Sequences 13 13 See Table 3-1 in HS, p. 44. Zheng-Liang Lu Java Programming 72 / 146

Boolean Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. boolean is also the type required by the conditional expressions that govern the control statements such as if and for. Note that a boolean value cannot be cast into a value of another type, nor can a value of another type be cast into a boolean value. Zheng-Liang Lu Java Programming 73 / 146

Rational Operators 14 They are all binary operators. Rational expressions return Boolean values. Note that the equality comparison operator is two equal signs (==), not a single equal sign (=), which is the assignment operator. 14 See Table 3-1 in YDL, p. 82. Zheng-Liang Lu Java Programming 74 / 146

Example 1... 2 a = 4 > 3; 3 b = 4 < 3; 4 c = 4 == 3; 5 d = 4!= 3; 6 e = 4 > 3 > 2; 7... a =? b =? c =? d =? e =? Be aware that e is logically correct but syntaxically wrong. Zheng-Liang Lu Java Programming 75 / 146

Logical Operators 15 Sometimes, whether a statement is executed is determined by a combination of several conditions. For example, 4 > 3 > 2 should be (4 > 3)&&(3 > 2) in the program, where && refers to the and operator. 15 See Table 3-2 in YDL, p. 102. Zheng-Liang Lu Java Programming 76 / 146

Arithmetic Compound Assignment Operators += ( =) is called the addition (subtraction) assignment operator. The increment (++) and decrement ( ) operators are for incrementing and decrementing a variable by 1. Zheng-Liang Lu Java Programming 77 / 146

Example 1... 2 int a = 1; 3 System.out.println(a+=1); // a = a + 1 4 System.out.println(a++); // a = a + 1 5 System.out.println(++a); // a = a + 1 6 System.out.println( a); // a = a 1 7 System.out.println(a ); // a = a 1 8... What are the results? Zheng-Liang Lu Java Programming 78 / 146

Bitwise Operators Java defines several bitwise operators that can be applied to the integer types: long, int, short, char, and byte. Zheng-Liang Lu Java Programming 79 / 146

Example 1... 2 int a = 3; // 0 + 2 + 1 or 0011 in binary 3 int b = 6; // 4 + 2 + 0 or 0110 in binary 4 int c = a b; 5 int d = a & b; 6 int e = a ˆ b; 7 int f = ( a & b) (a & b); 8 int g = a & 0x0f; 9 System.out.println(a >>= 2); 0 System.out.println(b <<= 2); 1... c =? d =? e =? f =? g =? h =? i =? In Line 9 and 10, what are the results? Zheng-Liang Lu Java Programming 80 / 146

Operator Precedence 16 16 See Table3-10 in YDL, p. 116. Zheng-Liang Lu Java Programming 81 / 146

A Tip: Using Parentheses Parentheses raise the precedence of the operations that are inside them. Adding parentheses to reduce ambiguity does not negatively affect your program. Zheng-Liang Lu Java Programming 82 / 146

Scanner Class It is not convenient to modify the source code and recompile it for a different radius. Reading input from the console enables the program to receive input from the user. Scanner class provides methods for console input. Java uses System.in to refer to the standard input device. By default, the input device is the keyboard. Zheng-Liang Lu Java Programming 83 / 146

Example: Reading Input From The Console Write a program which receives a number as input, and determine the area of the circle. 1 import java.util.scanner; // import a class 2... 3 Scanner input = new Scanner(System.in); // create an object 4... 5 radius = input.nextdouble(); // return a double to radius 6... 7 input.close(); 8... Zheng-Liang Lu Java Programming 84 / 146

1 import java.util.scanner; 2 3 public class ComputeAreaWithConsoleInput { 4 public static void main (String[] args) { 5 Scanner input = new Scanner(System.in); 6 System.out.println("Enter a number for radius: "); 7 double radius = input.nextdouble(); 8 double area = radius radius 3.1415926; 9 System.out.println("The area for the circle of radius " 0 + radius + " is " + area +"."); 1 input.close(); 2 } 3 } In the listing, Scanner input = new Scanner(System.in) creates a Scanner object and assigns its memory address to the variable input. So, input is a referential type variable. We will discuss the objects and referential variables in detail. Zheng-Liang Lu Java Programming 85 / 146

Methods Within Scanner Objects 17 17 See Table 2-1 in YDL, p. 38. Zheng-Liang Lu Java Programming 86 / 146

Example: Mean and Standard Deviation Write a program which calculates the sample mean and the sample standard deviation of any 3 numbers. Sample mean of three numbers is given by µ = Also, the sample standard deviation is given by 3 i=1 x i. 3 σ = 3 You may use these two methods: Math.pow(double x, double y) for x y Math.sqrt(double x) for x See more methods within Math class. i=1 (x i µ) 2. 2 Zheng-Liang Lu Java Programming 87 / 146

1... 2 public static void main (String[] args) { 3 Scanner input = new Scanner(System.in); 4 System.out.println("Enter a =?"); 5 double a = input.nextdouble(); 6 System.out.println("Enter b =?"); 7 double b = input.nextdouble(); 8 System.out.println("Enter c =?"); 9 double c = input.nextdouble(); 0 double mean = (a + b + c) / 3; 1 a = mean; // Deviation from mean 2 b = mean; 3 c = mean; 4 double std = Math.pow(a,2) + Math.pow(b,2) + Math.pow(c,2); 5 std /= 2; 6 std = Math.sqrt(std); 7 System.out.println("Mean = " + mean + "\n 8 Standard Deviation = " + std); 9 } 0... Zheng-Liang Lu Java Programming 88 / 146

Problem Set Exercise 2.1 (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows: yf = ( 9 5 ) xc + 32 Exercise 2.2 (Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. Zheng-Liang Lu Java Programming 89 / 146

Exercise 2.3 (Find the number of years) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days. Exercise 2.4 (Heron s formula.) Write a program that prompts the user to enter three points (x 1, y 1 ), (x 2, y 2 ), (x 3, y 3 ) of a triangle and displays its area. Zheng-Liang Lu Java Programming 90 / 146

Exercise 2.5 (Return rate) Write a program that reads in investment amount X, future value of investment Y, and number of years n, and displays the return rate of the investment r using the following formula: r = n Y X 1. Zheng-Liang Lu Java Programming 91 / 146

1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 / References 8 [1] Ch. 3 in YDL 9 / Zheng-Liang Lu Java Programming 92 / 146

Flow Controls The basic algorithm or program constitutes the following operations: Sequential operations: instructions executed in order. Selective operations: first check if the condition is satisfied, then select the next instruction based on boolean values. Repetitive operations: repeat the execution of a block of instructions until the criteria is not satisfied. Zheng-Liang Lu Java Programming 93 / 146

Note that the three types of operations are not mutually exclusive. In most cases, they are involved with each other. For example, recall how to find the highest score of math quiz in the class? Zheng-Liang Lu Java Programming 94 / 146

Selections Java has several types of selection statements: one-way if statements two-way if-else statements nested if statements switch-case statements conditional expressions Zheng-Liang Lu Java Programming 95 / 146

One-Way if Statements A one-way if statement executes an action if and only if the condition is true. Zheng-Liang Lu Java Programming 96 / 146

1 if (condition) { 2 // selection body 3 } The keyword if is followed by the parenthesized condition. The condition should be a boolean expression or a boolean value. It the condition is true, then the statements in the selection body will be executed once. If not, then the program won t enter the selection body. Note that the braces can be omitted if the block contains a single statement. Zheng-Liang Lu Java Programming 97 / 146

Example Write a program which receives a nonnegative number as input for the radius of a circle, and determines the area of the circle. 1... 2 if (radius >= 0) { 3 area = radius radius 3.1415926; 4 System.out.println("The area of the circle with radius " + 5 radius + " is " + area + "."); 6 } 7... But, the world is not well-defined. Zheng-Liang Lu Java Programming 98 / 146

Two-Way if-else Statements A two-way if-else statement decides which statements to execute based on whether the condition is true or false. 1 if (condition) { 2 // selection body 1 3 } 4 else { 5 // selection body 2 6 } Zheng-Liang Lu Java Programming 99 / 146

Zheng-Liang Lu Java Programming 100 / 146

Example Write a program which receives a number as input for the radius of a circle. If the number is nonnegative, then determine the area of the circle; otherwise, print Not a circle. 1... 2 if (radius >= 0) { 3 area = radius radius 3.1415926; 4 System.out.println("The area of the circle with radius " + radius + " is " + area + "."); 5 } 6 else { 7 System.out.println("Not a circle."); 8 } 9... Zheng-Liang Lu Java Programming 101 / 146

Example: Nested if Statements An if statement can be inside another if statement to form a nested if statement. 1... 2 if (score >= 90) System.out.println("A"); 3 else { 4 if (score >= 80) System.out.println("B"); 5 else { 6 if (score >= 70) System.out.println("C"); 7 else { 8 if (score >= 60) System.out.println("D"); 9 else System.out.println("F"); 0 } 1 } 2 } 3... Zheng-Liang Lu Java Programming 102 / 146

Example: Multi-Way if-else 1... 2 if (score >= 90) System.out.println("A"); 3 else if (score >= 80) System.out.println("B"); 4 else if (score >= 70) System.out.println("C"); 5 else if (score >= 60) System.out.println("D"); 6 else System.out.println("F"); 7... An if-elseif-else statement is a preferred format for multiple alternatives, in order to avoid deep indentation and makes the program easy to read. The order of conditions may be relevant. (Why?) The performance may degrade due to the order of conditions. (Why?) Zheng-Liang Lu Java Programming 103 / 146

Common Errors in Selection Statements Two bugs? 1... 2 if (r > 0); 3 area = r r pi; 4 System.out.println("Area = " + area); 5... How to revise in order to determine the maximum? 1... 2 int i = 1, j = 2, k = 3; 3 if (i > j) 4 if (i > k) 5 System.out.println("Max = " + i); 6 else if (j > k) 7 System.out.println("Max = " + j); 8 else 9 System.out.println("Max = " + k); 0... Zheng-Liang Lu Java Programming 104 / 146

Example Generating random numbers 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. Zheng-Liang Lu Java Programming 105 / 146

1... 2 public static void main(string[] args) { 3 4 int x = (int) (Math.random() 10); // numbers 0 9 5 int y = (int) (Math.random() 10); 6 7 System.out.println(x + " + " + y + " =?"); 8 9 Scanner in = new Scanner(System.in); 0 int z = in.nextint(); 1 2 if (z == (x + y)) 3 System.out.println("Correct."); 4 else 5 System.out.println("Wrong. The correct answer is " + (x + y ) + "."); 6 in.close(); 7 } 8... Can you extend this program to include + in the math expressions? Zheng-Liang Lu Java Programming 106 / 146

Exercise Find Maximum Write a program which finds the maximum value in 3 random integers whose range from 1 to 10. How many variables do we need? How to compare? How to keep the maximum value? Zheng-Liang Lu Java Programming 107 / 146

1... 2 public static void main(string[] args) { 3 4 int x = (int) (Math.random() 10 + 1); 5 int y = (int) (Math.random() 10 + 1); 6 int z = (int) (Math.random() 10 + 1); 7 8 System.out.println("(x, y, z) = " + "(" + x + "," + y + "," + z + ")"); 9 0 int max = x; 1 if (y > max) max = y; 2 if (z > max) max = z; 3 System.out.println("Max = " + max); 4 } 5... In this case, a scalar variable is not convenient. (Why?) Zheng-Liang Lu Java Programming 108 / 146

switch-case Statements A switch-case statements executes statements based on the value of a variable or an expression. 1 switch (target) { 2 case value1: 3 statements; 4 break; 5 case value2: 6. 7. 8 case valuek: 9 statements; 0 break; 1 default: 2 statements; 3 } Zheng-Liang Lu Java Programming 109 / 146

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

Example Write a program which picks a day of week randomly. How many discrete cases? Zheng-Liang Lu Java Programming 111 / 146

1 public class weekday { 2 public static void main(string[] args) { 3 int day = (int) ((Math.random() 10) % 7 + 1); 4 switch(day) { 5 case 1: 6 System.out.println("Monday"); 7 break; 8 case 2: 9 System.out.println("Tuesday"); 0 break; 1 case 3: 2 System.out.println("Wednesday"); 3 break; 4 case 4: 5 System.out.println("Thursday"); 6 break; 7 case 5: 8 System.out.println("Friday"); 9 break; 0 case 6: 1 System.out.println("Saturday"); 2 break; 3 case 7: 4 System.out.println("Sunday"); 5 break; Zheng-Liang Lu Java Programming 112 / 146

6 default: 7 System.out.println("Invalid weekday?"); 8 } 9 } 0 } Be aware that the arithmetic expression in Line 3 should be parenthesized. (Why?) Zheng-Liang Lu Java Programming 113 / 146

Conditional Expressions A conditional expression evaluates an expression based on a condition. 1 boolean expr? expr A : expr B; If the boolean expression is true, then the result is expr A; otherwise, expr B. Zheng-Liang Lu Java Programming 114 / 146

For example, 1... 2 if (num1 > num2) 3 max = num1; 4 else 5 max = num2; 6... Alternatively, one can use a conditional expression like this: 1... 2 y = (num1 > num2)? num1 : num2; 3... Be aware that an extreme concise expression is not always good. 19 19 Recall the reason why we develop so many high-level programming languages. Zheng-Liang Lu Java Programming 115 / 146

Formatting Console Output You can use System.out.printf () to display formatted output on the console. 1... 2 double amount = 12618.98; 3 double interestrate = 0.0013; 4 double interest = amount interestrate; 5 System.out.printf("Interest = %4.2f", interest); 6... Zheng-Liang Lu Java Programming 116 / 146

By default, a floating-point value is displayed with 6 digits after the decimal point. Zheng-Liang Lu Java Programming 117 / 146

Example: Multiple Items Items must match the format specifiers in order, in number, and in exact type. If an item requires more spaces than the specified width, the width is automatically increased. By default, the output is right justified. You can put the minus sign (-) in the format specifier to specify that the item is left justified in the output within the specified field. Zheng-Liang Lu Java Programming 118 / 146

Problem Set 20 Exercise 3.1 (Roots of 2 nd -order polynomials) Write a program which solves y = ax 2 + bx + c for all x, a, b, c R using the following formula: x = b ± b 2 4ac. 2a Note that a complex root and its conjugate are allowed in general. Zheng-Liang Lu Java Programming 119 / 146

Exercise 3.2 (Game: scissor, rock, paper) Write a program that plays the popular scissor-rockpaper game. The program randomly generates a number 0, 1, or 2 representing scissor, rock, and paper. The program prompts the user to enter a number 0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. Zheng-Liang Lu Java Programming 120 / 146

Exercise 3.3 (Sort three integers) Write a program that sorts three integers. The integers are entered from the input dialogs and stored in 3 variables. For example, the input is a = 1, b = 5, c = 2. Then the program display the 3 numbers in ascending order, that is, 1 < 2 < 5. Exercise 3.4 (Compute the perimeter of a triangle) Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge. Zheng-Liang Lu Java Programming 121 / 146

Exercise 3.5 (Geometry: points in triangle?) Suppose a right triangle is placed in a plane as shown below. The right-angle point is placed at (0, 0), and the other two points are placed at (200, 0), and (0, 100). Write a program that prompts the user to enter a point with x- and y-coordinates and determines whether the point is inside the triangle. Exercise 3.6 (Geometry: point in a circle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the circle centered at (0, 0) with radius 10. Zheng-Liang Lu Java Programming 122 / 146

Exercise 3.7 (Game: pick a card) Write a program that simulates picking a card from a deck of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of the card. Exercise 3.8 (Finance: currency exchange) Write a program that prompts the user to enter the exchange rate from currency in USD to TWD. Prompt the user to enter 0 to convert from USD to TWD and 1 to convert from TWD and USD. Prompt the user to enter the amount in USD or TWD to convert it to TWD or USD, respectively. 20 See Programming Exercises in YDL, p. 121-131. Zheng-Liang Lu Java Programming 123 / 146

1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 124 / 146

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

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

Flow Controls (Recap) The concept of looping, which is one of elements in algorithms, is fundamental to programming. Loops provide significant computation power. Loops bring an efficient way of programming. Loops could consume a lot of time. 22 22 We will visit the analysis of algorithms soon. Zheng-Liang Lu Java Programming 127 / 146

while Loops A while loop executes statements repeatedly while the condition is true. 1... 2 while (condition) { 3 // loop body 4 } 5... The condition is a Boolean expression which controls the execution of the body. It is evaluated each time to determine if the loop body is executed. If true, the loop body is executed. Otherwise, the entire loop terminates. Zheng-Liang Lu Java Programming 128 / 146

Zheng-Liang Lu Java Programming 129 / 146

Example Write a program which sums up all integers from 1 to 100. In math, the question can be: sum = 1 + 2 + + 100. But the form is not doable in a computer. What is?! Think in a programmer s way. Zheng-Liang Lu Java Programming 130 / 146

Normally, the computer executes the instructions sequentially. 23 So, one needs to decompose the math equation into several lines, like: 1 int sum = 0; 2 sum = sum + 1; 3 sum = sum + 2; 4. 5. 6. 7 sum = sum + 100; Cons: Not efficient, not general (what if sum up to 10 10?) 23 If we are talking about the parallel computing, then it is a different world. Zheng-Liang Lu Java Programming 131 / 146

Using a while loop, the program looks like this: 1... 2 int sum = 0; 3 int i = 0; 4 while (++i <= 100) 5 sum = sum + i; 6... Make sure that the condition eventually becomes false so that the loop will terminate. It is really easy to make an infinite loop. 1... 2 while(true); 3... Zheng-Liang Lu Java Programming 132 / 146

Besides, replacing 100 by n determined by the user makes this program more general. 1... 2 Scanner input = new Scanner(System.in); 3 int n = input.nextint(); 4 int sum = 0; 5 int i = 0; 6 while (++i <= n) 7 sum = sum + i; 8... In practice, the number of loop steps is unknown until the input data is given. For example, the bisection algorithm 24 provides a numerical solution to root-finding problems. 24 http://en.wikipedia.org/wiki/bisection_method Zheng-Liang Lu Java Programming 133 / 146

Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 public static void main (String[] args) { 3 // random integer generation 4 int number1 = (int)(math.random() % 10); 5 int number2 = (int)(math.random() % 10); 6 7 Scanner input = new Scanner(Sysmte.in); 8 System.out.println(number1 + " + " + number2 + " =?"); 9 int ans = input.nextint(); 0 1 while (number1 + number2!= ans) { 2 System.out.println("Wrong answer. Try again?"); 3 ans = input.nextint(); 4 } 5 System.out.println("Congrats! You are smart!"); 6 } 7... Zheng-Liang Lu Java Programming 134 / 146

Exercise 25 Write a program which runs for a predetermined time, say, one minute, and terminates itself. You may use System.currentTimeMillis() to produce a time stamp. 25 Contribution by Ms. Hsu, Tzu-Hen (JB25318) on June 6, 2015. Zheng-Liang Lu Java Programming 135 / 146

1... 2 public static void main(string[] args) { 3 Scanner input = new Scanner(System.in); 4 long t0 = System.currentTimeMillis(); 5 System.out.println("Duration? (ms) "); 6 long interval = input.nextint(); 7 input.close(); 8 while (System.currentTimeMillis() <= t0 + interval) 9 System.out.println("Running..."); 0 System.out.println("End."); 1 } 2... Zheng-Liang Lu Java Programming 136 / 146

Loop Design Strategies 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: Wrap these statements in a loop. Set the continuation condition 26 26 Not unique. Zheng-Liang Lu Java Programming 137 / 146

Sentinel-Controlled Loop 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. Zheng-Liang Lu Java Programming 138 / 146

Example Write a program which sums real numbers from the input except for -1 to exit, and displays the sum. 1... 2 Scanner in = new Scanner(System.in); 3 double sum = 0; 4 System.out.println("Enter a positive integer ( 1 to exit): "); 5 double x = in.nextdouble(); 6 while(x!= 1) { 7 sum += x; 8 System.out.println("Enter a positive integer ( 1 to exit): "); 9 x = in.nextdouble(); 0 } 1 System.out.println("Sum = " + sum); 2 in.close(); 3... Line 8 and 9 are the recurrence of Line 4 and 5?! Zheng-Liang Lu Java Programming 139 / 146

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

Zheng-Liang Lu Java Programming 141 / 146

Example Write a program which allows the user to enter positive integers except for -1 to exit, and displays the maximum. Zheng-Liang Lu Java Programming 142 / 146

1... 2 Scanner in = new Scanner(System.in); 3 int max = 0, x; 4 do{ 5 System.out.println("Please enter a positive integer ( 1 to exit): "); 6 x = in.nextint(); 7 if(max < x) { 8 max = x; 9 } 0 System.out.println("Max = " + max); 1 } while(x!= 1); 2 in.close(); 3... Zheng-Liang Lu Java Programming 143 / 146

for Loops A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. 1... 2 for(init; condition; increment) { 3 // loop body 4 } 5... init: initialize a variable condition: a criteria that a loop continues increment: how the variable changes after each iteration Note that the three terms are separated by a semicolon. Zheng-Liang Lu Java Programming 144 / 146

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

Zheng-Liang Lu Java Programming 146 / 146