1. Requirements: Design a method that can achieve random numbers in any range
Analysis: How to use random () is as follows:
1 Public Static Double random () 2 Note: 0.0 (inclusive) 1.0 (Exclusive). //0.0 <= x <1.0
(1) keyboard input two number.
1 int start; 2 int End
(2) Find a way to get the random number between start and end
(3) Output this random number
2. Code implementation:
1 Packagecn.itcast_02;2 3 ImportJava.util.Scanner;4 5 /*6 * Requirements: Please design a method that can achieve random numbers in any range. 7 * 8 * Analysis:9 * A: Keyboard input two data. Ten * int strat; One * int end; A * B: Find a way to get the random number between start and end - * I write a function to achieve this effect and get a random number. (int) - * C: Output This random number the */ - Public classMathdemo { - Public Static voidMain (string[] args) { -Scanner sc =NewScanner (system.in); +System.out.println ("Please enter start number:"); - intStart =sc.nextint (); +System.out.println ("Please enter end number:"); A intEnd =sc.nextint (); at - for(intx = 0; x < 100; X + +) { - //Invoke function - intnum =getrandom (start, end); - //Output Results - System.out.println (num); in } - } to + /* - * Write a function two explicit: return value type: int argument list: int Start,int end the */ * Public Static intGetrandom (intStartintend) { $ //think back to the random numbers we talked about between 1-100.Panax Notoginseng //int number = (int) (Math.random () * +) + 1;//(int) (Math.random () *100)-- 0 <= x <100, then (math.random () *100+1)-- 1<=x<101 - //int number = (int) (Math.random () * end) + start; the //found a problem, how to do it? + intNumber = (int) (Math.random () * (End-start + 1)) +start;// start <= x <= End A returnNumber ; the } +}
The results are as follows:
Java Fundamentals Hardening 82:math Class Random () method to obtain arbitrary range of randomly-number cases (interview questions)