330 likes | 340 Views
Explore advanced techniques for random number generation and repeatability in Java programming, including scaling and shifting values, seeded sequences, and using Random class. Learn to create controlled random sequences for testing and debugging.
E N D
6.9 Case Study: Random-Number Generation • Random-number (隨機數字) generation 有兩個方式: • static method random from class Math • Math.random( ) • Returns doubles 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個隨機數字的值決定,之後的值都由前一個值決定
Outline Import class Random from the java.util package RandomIntegers .java (1 of 2) Create a Random object Generate a random die roll
Outline Two different sets of results containing integers in the range 1-6 RandomIntegers .java (2 of 2)
Outline Import class Random from the java.util package RollDie.java (1 of 2) Create a Random object Declare frequency counters
Outline Iterate 6000 times RollDie.java (2 of 2) Generate a random die roll switch based on the die roll
Outline Display die roll frequencies • RollDie.java • (3 of 3)
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
練習 • 以 random number 表示以下範圍的整數: • 1 n 2 1 + r1.nextInt(2) • 1 n 100 1 + r1.nextInt(100) • 0 n 9 r1.nextInt(10) • 1000 n 1112 1000 + r1.nextInt(13) • -1 n 1 -1 + r1.nextInt(3) • -3 n 11 -3 + r1.nextInt(15) • 2, 4, 6, 8, 10 2+2*r1.nextInt(5) • 3, 5, 7, 9, 11 3+2*r1.nextInt(5) • 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
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:RandomrandomNumbers= newRandom(seedValue); • Use the setSeed method:randomNumbers.setSeed(seedValue); • seedValue should be an argument of type long
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.
Outline Import class Random from the java.util package • Craps.java • (1 of 4) Create a Random object Declare an enumeration Declare constants
Outline Call rollDice method • Craps.java • (2 of 4) Player wins with a roll of 7 or 11 Player loses with a roll of 2, 3 or 12 Set and display the point
Outline Call rollDice method • Craps.java • (3 of 4) Player wins by making the point Player loses by rolling 7 Display outcome
Outline Declare rollDice method • Craps.java • (4 of 4) Generate two dice rolls Display dice rolls and their sum
Outline • CrapsTest.java • (1 of 2)
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 ints
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.
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
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
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)
Outline • Scope.java • (1 of 2) Shadows field x Display value of local variable x
Outline Shadows field x • Scope.java • (2 of 2) Display value of local variable x Display value of field x
Outline • ScopeTest.java
練習 • 請問 fig06_09_10 中的 Craps.java程式裡,以下變數或方法之有效範圍(結果請以 “第 x 列 –第 y 列”表示): • 變數 randomNumbers • 變數 die1 • 方法 rollDice • 方法 play • 變數 sumOfDice • 請再以 isPrime( ) 方法,參數為一正整數,寫一遍第 6 次小考的程式
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
Outline Correctly calls the “square of int” method • MethodOverload.java Correctly calls the “square of double” method Declaring the “square of int” method Declaring the “square of double” method
Outline • MethodOverloadTest.java
Outline • MethodOverload • Error.java Same method signature Compilation error
Common Programming Error 6.11 • Declaring overloaded methods with identical parameter lists is a compilation error regardless of whether the return types are different.
練習 • 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 中的完美數字,列印時請將其因數一併印出,以利檢驗。
練習 • Ex6_30: 猜數字遊戲 (Guess) • 請寫一程式來玩猜數字遊戲 ,每次遊戲程式會產生一個介於 1 到 100 的正整數,請使用者持續猜到那個數字為止。 • 如果使用者猜的答案太大,則回應 “太大”;並請使用者 • 繼續猜。 • 2. 如果使用者猜的答案太小,則回應 “太小”;並請使用者繼續猜。 • 3. 如果使用者猜對了,則回應 “Bingo”,並問使用者 • ”要不要再玩?”。 • 3.1 使用者回答 ”要”的話,就開始下一新回合, • 3.2 使用者回答 ”不要”的話,就結束程式。
期末重點提示 • if (含 logical operators) • while • for • switch • break, continue • 物件導向 (方法、實體變數、static) • Math, Random • enum • overload • argument promotion, type casting • precedence and associativity of operators
練習 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() 方法。