Download presentation
Presentation is loading. Please wait.
Published byJoella Bishop Modified over 9 years ago
1
1992-2007 Pearson Education, Inc. All rights reserved. 1 6.9 Case Study: Random-Number Generation Random-number ( 隨機數字 ) generation 有兩個方 式: – static method random from class Math Math.random( ) Returns double s in the range 0.0 x < 1.0 – Thru object of class Random from package java.util Can produce pseudorandom boolean, byte, float, double, int, long and Gaussian values – 如 nextInt() 、 nextDouble() 等方法 ( 請參見範例 ) Is seeded with the current time of day to generate different sequences of numbers each time the program executes ,種子數 用來決定第 1 個隨機數字的值,第 2 個隨機數字的值由第 1 個 隨機數字的值決定,之後的值都由前一個值決定
2
1992-2007 Pearson Education, Inc. All rights reserved. 2 Outline RandomIntegers.java (1 of 2) Import class Random from the java.util package Create a Random object Generate a random die roll
3
1992-2007 Pearson Education, Inc. All rights reserved. 3 Outline RandomIntegers.java (2 of 2) Two different sets of results containing integers in the range 1-6
4
1992-2007 Pearson Education, Inc. All rights reserved. 4 Outline RollDie.java (1 of 2) Import class Random from the java.util package Declare frequency counters Create a Random object
5
1992-2007 Pearson Education, Inc. All rights reserved. 5 Outline RollDie.java (2 of 2) Iterate 6000 times Generate a random die roll switch based on the die roll
6
1992-2007 Pearson Education, Inc. All rights reserved. 6 Outline RollDie.java (3 of 3) Display die roll frequencies
7
1992-2007 Pearson Education, Inc. All rights reserved. 7 6.9.1 Generalized Scaling and Shifting of Random Numbers To generate a random number in certain sequence or range ( 有規律的數字序列才可以 ) – Use the expression shiftingValue + differenceBetweenValues *randomNumbers.nextInt( scalingFactor ) where: shiftingValue ( 初值 ) is the first number in the desired range of values differenceBetweenValues ( 差值 ) represents the difference between consecutive numbers in the sequence scalingFactor ( 個數 ) specifies how many numbers are in the range – 例如:介於 3 到 10 間的整數 3 + 1 * randomNumbers.nextInt(8) – 例如:由 7, 14, 21, 28, 35 間隨機產生 7 + 7 * randomNumbers.nextInt(5) – 那怎麼處理沒有規律的數字序列,例如 3, 5, 13, 15, 33, 37 用 switch
8
1992-2007 Pearson Education, Inc. All rights reserved. 8 練習 以 random number 表示以下範圍的整數: (a)1 n 2 1 + r1.nextInt(2) (b)1 n 100 1 + r1.nextInt(100) (c)0 n 9 r1.nextInt(10) (d)1000 n 1112 1000 + r1.nextInt(13) (e)-1 n 1 -1 + r1.nextInt(3) (f)-3 n 11 -3 + r1.nextInt(15) (g)2, 4, 6, 8, 10 2+2*r1.nextInt(5) (h)3, 5, 7, 9, 11 3+2*r1.nextInt(5) (i)6, 10, 14, 18, 22 6 + 4 * r1.nextInt(5) 四捨五入到整數 Math.round( x ) or Math.floor( x + 0.5) 四捨五入到小數點後第 1 位,請類推四捨五入到小數點後第 n 位 Math.floor( 10 * (x + 0.05) ) / 10.0
9
1992-2007 Pearson Education, Inc. All rights reserved. 9 6.9.2 Random-Number Repeatability for Testing and Debugging To get a Random object to generate the same sequence of random numbers every time the program executes, seed it with a certain value – When creating the Random object: Random randomNumbers = new Random( seedValue ); – Use the setSeed method: randomNumbers.setSeed( seedValue ); – seedValue should be an argument of type long
10
1992-2007 Pearson Education, Inc. All rights reserved. 10 Error-Prevention Tip 6.2 While a program is under development( 還在開發中 ), create the Random object with a specific seed value to produce a repeatable ( 可重覆的 ) sequence of random numbers each time the program executes. If a logic error occurs, fix the error and test the program again with the same seed value-this allows you to reconstruct the same sequence of random numbers that caused the error. Once the logic errors have been removed, create the Random object without using a seed value, causing the Random object to generate a new sequence of random numbers each time the program executes.
11
1992-2007 Pearson Education, Inc. All rights reserved. 11 Outline Craps.java (1 of 4) Import class Random from the java.util package Create a Random object Declare an enumeration Declare constants
12
1992-2007 Pearson Education, Inc. All rights reserved. 12 Outline Craps.java (2 of 4) Call rollDice method Player wins with a roll of 7 or 11 Player loses with a roll of 2, 3 or 12 Set and display the point
13
1992-2007 Pearson Education, Inc. All rights reserved. 13 Outline Craps.java (3 of 4) Call rollDice method Player wins by making the point Player loses by rolling 7 Display outcome
14
1992-2007 Pearson Education, Inc. All rights reserved. 14 Outline Craps.java (4 of 4) Generate two dice rolls Declare rollDice method Display dice rolls and their sum
15
1992-2007 Pearson Education, Inc. All rights reserved. 15 Outline CrapsTest.java (1 of 2)
16
1992-2007 Pearson Education, Inc. All rights reserved. 16 6.10 Case Study: A Game of Chance (Introducing Enumerations) Enumerations – Programmer-declared types consisting of sets of constants – enum keyword – A type name (e.g. Status ) – Enumeration constants (e.g. WON, LOST and CONTINUE ) cannot be compared against int s
17
1992-2007 Pearson Education, Inc. All rights reserved. 17 Good Programming Practice 6.3, 6.4 Use only uppercase letters in the names of constants. This makes the constants stand out in a program and reminds the programmer that enumeration constants are not variables. Using enumeration constants (like Status.WON, Status.LOST and Status.CONTINUE) rather than literal integer values (such as 0, 1 and 2) can make programs easier to read and maintain.
18
1992-2007 Pearson Education, Inc. All rights reserved. 18 6.11 Scope of Declarations ( 宣告的有效範圍 ) Basic scope rules – Scope of a parameter declaration ( 方法參數 ) is the body of the method in which appears – Scope of a local-variable ( 區域變數 ) declaration is from the point of declaration to the end of that block ( 區塊 ) – Scope of a local-variable declaration in the initialization section of a for header is the rest of the for header and the body of the for statement – Scope of a method or field of a class is the entire body of the class
19
1992-2007 Pearson Education, Inc. All rights reserved. 19 6.11 Scope of Declarations (Cont.) Shadowing ( 覆蓋 ) – A field is shadowed (or hidden ,不能用 ) if a local variable or parameter has the same name as the field This lasts until the local variable or parameter goes out of scope
20
1992-2007 Pearson Education, Inc. All rights reserved. 20 Common Programming Error 6.10 A compilation error occurs when a local variable is declared more than once in a method. Use different names for fields and local variables to help prevent subtle logic errors that occur when a method is called and a local variable of the method shadows a field of the same name in the class. ( 範例 6-11)
21
1992-2007 Pearson Education, Inc. All rights reserved. 21 Outline Scope.java (1 of 2) Shadows field x Display value of local variable x
22
1992-2007 Pearson Education, Inc. All rights reserved. 22 Outline Scope.java (2 of 2) Shadows field x Display value of local variable x Display value of field x
23
1992-2007 Pearson Education, Inc. All rights reserved. 23 Outline ScopeTest.java
24
1992-2007 Pearson Education, Inc. All rights reserved. 24 練習 請問 fig06_09_10 中的 Craps.java 程式裡,以下變 數或方法之有效範圍 ( 結果請以 “ 第 x 列 – 第 y 列 ” 表示 ) : 變數 randomNumbers 變數 die1 方法 rollDice 方法 play 變數 sumOfDice 請再以 isPrime( ) 方法,參數為一正整數,寫一遍第 6 次小考的程 式
25
1992-2007 Pearson Education, Inc. All rights reserved. 25 6.12 Method Overloading Method overloading ( 多載 ) – Multiple methods with the same name, but different types, number or order of parameters in their parameter lists – Compiler decides which method is being called by matching the method call ’ s argument list to one of the overloaded methods ’ parameter lists A method ’ s name and number, type and order of its parameters form its signature – Differences in return type are irrelevant ( 不相干 ) in method overloading Overloaded methods can have different return types Methods with different return types but the same signature cause a compilation error
26
1992-2007 Pearson Education, Inc. All rights reserved. 26 Outline MethodOverload.java Correctly calls the “ square of int ” method Correctly calls the “ square of double ” method Declaring the “ square of int ” method Declaring the “ square of double ” method
27
1992-2007 Pearson Education, Inc. All rights reserved. 27 Outline MethodOverloadTest.java
28
1992-2007 Pearson Education, Inc. All rights reserved. 28 Outline MethodOverload Error.java Same method signature Compilation error
29
1992-2007 Pearson Education, Inc. All rights reserved. 29 Common Programming Error 6.11 Declaring overloaded methods with identical parameter lists is a compilation error regardless of whether the return types are different.
30
1992-2007 Pearson Education, Inc. All rights reserved. 30 Ex6_17: 請寫出以下方法的內容: fillSquare( int size, char fillCharacter ) 這方法會畫出以 fillCharacter 填滿之 size * size 的正方形,不需回傳任何 值。並請使用者輸入 size 及 fillCharacter 後,呼叫此方法加以測試。 Ex6_22: 一個數字被稱為 完美數字 (perfect number ) 如果其因數加總的和正 好等於該數,例如: 6 的因數有 1 、 2 、 3 ,而 6 = 1 + 2 +3 ,所以 6 是一個 perfect number 。請寫以下方法的內容: String perfect (int n) 這方法會檢查 n 是否為完美數字,如果是則傳回 n 的所有因數的字串,否則 傳回 null 物件。再請寫一應用程式列印出 2 至 1000 中的完美數字,列印時 請將其因數一併印出,以利檢驗。 練習
31
1992-2007 Pearson Education, Inc. All rights reserved. 31 練習 Ex6_30: 猜數字遊戲 (Guess) 請寫一程式來玩猜數字遊戲 ,每次遊戲程式會產 生一個介於 1 到 100 的正整數,請使用者持續 猜到那個數字為止。 如果使用者猜的答案太大,則回應 “ 太大 ” ;並請使用者 繼續猜。 2. 如果使用者猜的答案太小,則回應 “ 太小 ” ;並請使用者 繼續猜。 3. 如果使用者猜對了,則回應 “ Bingo ” ,並問使用者 ” 要不要再玩? ” 。 3.1 使用者回答 ” 要 ” 的話,就開始下一新回合, 3.2 使用者回答 ” 不要 ” 的話,就結束程式。
32
1992-2007 Pearson Education, Inc. All rights reserved. 32 期末重點提示 if ( 含 logical operators) while for switch break, continue 物件導向 ( 方法、實體變數、 static) Math, Random enum overload argument promotion, type casting precedence and associativity of operators
33
1992-2007 Pearson Education, Inc. All rights reserved. 33 練習 Ex6_30 (1) Guess2 類別中需含一個 正整數 實體變數 answer (2) Guess2 類別中要使用 enum 設計一個使用者自訂的資料型態 RESULT 用來設定使用者猜的數字跟答案比較的結果 太大 (TOO_BIG) 、 太小 (TOO_SMALL) 、 答對 (BINGO) (3) Guess2 類別的方法: 1. RESULT check(int n) : 比較使用者猜的數字跟答案,可能傳回 RESULT.TOO_BIG, RESULT.TOO_SMALL, 或 RESULT.BINGO 2. void newGame( ) : 代表使用者的新一回合,須完成以下動作 先將 answer 設定為一個隨機變數, 請使用者輸入一個數字 userGuess , 呼叫 check(userGuess) , 檢查結果直到 BINGO 為止,如果不是 BINGO ,持續 請使用者輸入一個數字 userGuess , 呼叫 check(userGuess) 問使用者要不要再玩, 要的話,呼叫 newGame() 以開啟下一回合 (4) 另外寫一 PlayGuess 類別來測試 Guess2 類別,其 main 方法需 生成一個 Guess2 物件,並呼叫該物件的 newGame() 方法。
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.