A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is.

Slides:



Advertisements
Similar presentations
Craps. /* * file : Craps.java * file : Craps.java * author: george j. grevera, ph.d. * author: george j. grevera, ph.d. * desc. : program to simulate.
Advertisements

1 JavaScript: Control Structures II. 2 whileCounter.html 1 2
Arrays part 2 Applications & such. Returning an array from a method A method can return an array, just like it can return any other kind of variable;
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 16 – Craps Game Application Introducing Random-Number.
Page 1 of 26 Javascript/Jscript Ch 7,8,9,10 Vadim Parizher Computer Science Department California State University, Northridge Spring 2003 Slides from.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 15.1 Test-Driving the Craps Game Application.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Introduction to Computers and Programming Lecture 12: Math.random() Professor: Evan Korth New York University.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Java: How to Program Methods Summary Yingcai Xiao.
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 12 – Craps Game Application: Introducing Random.
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
1 JavaScript/Jscript 4 Functions. 2 Introduction Programs that solve real-world programs –More complex than programs from previous chapters Best way to.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
1 Lecture 3 Part 1 Functions with math and randomness.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
MOM! Phineas and Ferb are … Aims:
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
4 th Week Spring 2011 Methods 1. Outline Introduction Why method ? Static methods vs. non-static methods Example: Math class Declare a method Signature.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 18 - WMLScript: Control Structures II Outline 18.1 Introduction 18.2 Essentials of Counter-Controlled.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Part II © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
 2008 Pearson Education, Inc. All rights reserved Case Study: Random Number Generation C++ Standard Library function rand – Introduces the element.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 16.1Introduction 16.2Program Modules in JavaScript 16.3Programmer-Defined Functions 16.4Function.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Header files and Library Functions) Outline.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
Chapter 6 Methods: A Deeper Look. Objectives In this chapter you will learn: How static methods and fields are associated with an entire class rather.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
Review for Nested loops & Math class methods & User defined methods.
CSci 162 Lecture 7 Martin van Bommel. Random Numbers Until now, all programs have behaved deterministically - completely predictable and repeatable based.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 – Methods Part I.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 16 – Craps Game Application Introducing Random-Number.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Part III © Copyright by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Introduction Program Components in C++ Math Library Functions Functions.
CISC181 Introduction to Computer Science Dr
Methods Chapter 6.
© 2016 Pearson Education, Ltd. All rights reserved.
The Random Class and its Methods
توابع در C++ قسمت اول اصول كامپيوتر 1.
Chapter 6 - Functions Outline 5.1 Introduction
MSIS 655 Advanced Business Applications Programming
Chapter 5 Methods: A Deeper Look
Presentation transcript:

A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is imported by compiler into all programs Java SE 8 for Programmers Paul Deitel &Harvey Deitel Deitel Developer Series 2014

Case Study: Secure Random-Number Generation  A popular type of programming application is simulation and game playing.  The element of chance can be introduced in a program via an object of class SecureRandom (package java.security).  Such objects can produce random boolean, byte, float, double, int, long values.

Class SecureRandom java.lang.Object java.util.Random java.security.SecureRandom public class SecureRandom extends Random  Random class is in java.utility  This class provides a cryptographically strong random number generator (RNG).

Moving to Secure Random Numbers from Random Numbers  Java’s Random class is used to obtain “random” values. This class produces deterministic values that could be predicted by malicious programmers.  SecureRandom objects produce nondeterministic random numbers that cannot be predicted.

A Note About Performance  Using SecureRandom instead of Random to achieve higher levels of security incurs a significant performance penalty.  It is possible to use class Random from package java.util  It is required simply to replace SecureRandom with Random.

Creating a SecureRandom Object A new secure random-number generator object can be created as SecureRandom randomNumbers = new SecureRandom();  It can then be used to generate random  For more information on the SecureRandom class docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html

Obtaining a Random int Value Consider the following statement int randomValue = randomNumbers.nextInt(); SecureRandom method nextInt generates a random int value. If it truly produces values at random, then every value in the range should have an equal chance (or probability) of being chosen each time nextInt is called

Changing the Range of Values Produced By nextInt  The range of values is produced by method nextInt  The method nextInt generally differs from the range of values required in any Java application.  A program that simulates coin tossing might require only 0 for “heads” and 1 for “tails.”  A program that simulates the rolling of a six- sided die might require random integers in the range 1–6.

Changing the Range of Values Produced By nextInt  class SecureRandom provides another version of method nextInt that receives an int argument and returns a value from 0 up to, but not including, the argument’s value.  For coin tossing, the following statement returns 0 or 1. int randomValue = randomNumbers.nextInt(2);

Rolling a Six-Sided Die  The program simulates 20 rolls of a six-sided die and displays the value of each roll.  nextInt produces random values in the range 0–5 int face = randomNumbers.nextInt(6);  The argument 6 is scaling factor  the number of values that nextInt should produce (0, 1, 2, 3, 4,5).  This manipulation is called scaling the range of values produced by SecureRandom method nextInt.  A six-sided die has the numbers 1–6 on its faces, not 0–5.  shift the range of numbers produced by adding a shifting value int face = 1 + randomNumbers.nextInt(6);  The shifting value (1) specifies the first value in the desired range of random integers. The preceding statement assigns face a random integer in the range 1–6.

import java.security.SecureRandom; // imports class SecureRandom from the java.security package. public class RandomIntegers { //each run of the program can produce a different sequence of random numbers public static void main(String[] args) { // creates the SecureRandom object randomNumbers to produce random values SecureRandom randomNumbers = new SecureRandom(); // loop 20 times for (int counter = 1; counter <= 20; counter++) { // pick random integer from 1 to 6 int face = 1 + randomNumbers.nextInt(6); System.out.printf("%d ", face); // display generated value // statement in the loop starts a new line of output after every five numbers if (counter % 5 == 0) System.out.println(); } } } // end class

Shifted and Scaled Random Integers

Rolling a Six-Sided Die 6,000,000 Times import java.security.SecureRandom; public class RollDie { public static void main(String[] args) { // randomNumbers object will produce secure random numbers SecureRandom randomNumbers = new SecureRandom(); int frequency1 = 0; // count of 1s rolled int frequency2 = 0; // count of 2s rolled int frequency3 = 0; // count of 3s rolled int frequency4 = 0; // count of 4s rolled int frequency5 = 0; // count of 5s rolled int frequency6 = 0; // count of 6s rolled // tally counts for 6,000,000 rolls of a die

…… for (int roll = 1; roll <= ; roll++) { int face = 1 + randomNumbers.nextInt(6); ……….; // number from 1 to 6 switch (face) { case 1: …… ;  Scaling and shifting the values produced by nextInt enables the program to simulate rolling a six-sided die.

…… // use face value 1-6 to determine which counter to increment switch (face) { case 1: ++frequency1; // increment the 1s counter break; case 2: ++frequency2; // increment the 2s counter break; case 3: ++frequency3; // increment the 3s counter break; case 4: ++frequency4; // increment the 4s counter break; case 5: ++frequency5; // increment the 5s counter break; case 6: ++frequency6; // increment the 6s counter break; }

Nested Control Statements for & switch case  T he switch is nested inside the for to determine the number of times each side of the die appears.  The for statement iterates 6,000,000 times.  During each iteration produces a random value from 1 to 6.  This value is used as the controlling expression of the switch statement  Based on the face value, the switch statement increments one of the six counter variables during each iteration of the loop.  The switch statement has no default case, because we have a case for every possible die value  Every time this program is run, it produces different results.

……. } //end for statement System.out.println("Face\tFrequency"); // output headers System.out.printf("1\t%d%n2\t%d%n3\t%d%n4\t%d%n5\t% d%n6\t%d%n", frequency1, frequency2, frequency3, frequency4, frequency5, frequency6); } //end main program } // end class RollDie

Roll a six-sided die 6,000,000 times Face Frequency Face Frequency

Generalized Scaling and Shifting of Random Numbers The rolling of a six-sided die is simulated with the statement int face = 1 + randomNumbers.nextInt(6);  This statement always assigns to variable face an integer in the range 1 ≤ face ≤ 6.  The width of the range is determined by the number 6  This number is passed as an argument to SecureRandom method nextInt  The starting number in the range is 1.  The starting number 1 of the range is added to randomNumbers.nextInt(6)

Generalized Scaling and Shifting of Random Numbers int number = shiftingValue + randomNumbers.nextInt(scalingFactor);  shiftingValue specifies the first number in the desired range of consecutive integers  scalingFactor specifies how many numbers are in the range.

Generalized Scaling and Shifting of Random Numbers  It’s possible to choose integers at random from sets of values other than ranges of consecutive integers.  A random value from the sequence 2, 5, 8, 11,14 int number = * randomNumbers.nextInt(5);  randomNumbers.nextInt(5) produces values in the range 0–4.  Each value produced is multiplied by 3 to produce a number in the sequence 0, 3, 6, 9 and 12.  We add 2 to that value to shift the range of values and obtain a value from the sequence 2, 5, 8, 11, 14.

The Generalized Expression int number = shiftingValue + differenceBetweenValues * randomNumbers.nextInt(scalingFactor);  shiftingValue specifies the first number in the desired range of values,  differenceBetweenValues represents the constant difference between consecutive numbers in the sequence  scalingFactor specifies how many numbers are in the range.

A Game of Chance Introducing enum Types 1.Roll two dice. Each die has six faces, which contain one, two, three, four, five and six spots 2. The sum of the spots on the two upward faces is calculated. 3. If the sum is 7 or 11 on the first throw, you win. If the sum is 2, 3 or 12 on the first throw, you lose 4. If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes your “point.” 4-a To win, you must continue rolling the dice until you “make your point” 4-b You lose by rolling a 7 before making your point.

import java.security.SecureRandom; public class Craps { // create secure random number generator for use in method rollDice private static final SecureRandom randomNumbers = new SecureRandom(); // enum type with constants that represent the game status private enum Status { CONTINUE, WON, LOST }; // constants that represent common rolls of the dice private static final int a = 2; private static final int b = 3; private static final int c = 7; private static final int d = 11; private static final int e = 12;

public static void main(String[] args) { int myPoint = 0; // point if no win or loss on first roll Status gameStatus; // can contain CONTINUE, WON or LOST int sumOfDice = rollDice(); // first roll of the dice // determine game status and point based on first roll switch (sumOfDice) { case c: // win with 7 on first roll case d: // win with 11 on first roll gameStatus = Status.WON; break; case a: // lose with 2 on first roll case b: / / lose with 3 on first roll case e: // lose with 12 on first roll gameStatus = Status.LOST; break; default: // did not win or lose, so remember point gameStatus = Status.CONTINUE; // game is not over myPoint = sumOfDice; // remember the point System.out.printf("Point is %d%n", myPoint); break; } …………………

// while game is not complete while (gameStatus == Status.CONTINUE) // not WON or LOST { sumOfDice = rollDice(); // roll dice again // determine game status if (sumOfDice == myPoint) // win by making point gameStatus = Status.WON; else if (sumOfDice == c // lose by rolling 7 before point gameStatus = Status.LOST; }

…………………………… // display won or lost message if (gameStatus == Status.WON) System.out.println("Player wins"); else System.out.println("Player loses"); } // roll dice, calculate sum and display results public static int rollDice() { // pick random die values int die1 = 1 + randomNumbers.nextInt(6); // first die rol int die2 = 1 + randomNumbers.nextInt(6); // second die roll int sum = die1 + die2; // sum of die values // display results of this roll System.out.printf("Player rolled %d + %d = %d%n", die1, die2, sum); return sum; } } // end class Craps

Player rolled = 11 Player wins Player rolled = 9 Point is 9 Player rolled = 6 Player rolled = 9 Player wins Player rolled = 3 Player loses Player rolled = 8 Point is 8 Player rolled = 6 Player rolled = 3 Player rolled = 7 Player loses