Design a method for java interview questions to obtain random numbers in any range.

Source: Internet
Author: User

Design a method for java interview questions to obtain random numbers in any range.

When learning java basics, you may listen to the random numbers between 1 and 100 at most, so we should first write a random number between 1 and 100. The Code is as follows,

 

public class MathDemo1 {         public static void main(String[] args) {         for(int i=0;i<100;i++){         System.out.println(getRandom());         }}         public static int getRandom(){        int number = (int) (Math.random() * 100) + 1;return number;         }}

In this loop, we want to check whether the random number is correct for 100 times, so our interview questions are random numbers in any range, such as 200 to 300. This is a range. Let's take a look.
int number = (int) (Math.random() * 100) + 1
Can this code be written like this? int number = (int) (Math. random () * (100-0) + 1;

 

Where can we regard 0 as a starting variable? 100 when the maximum value of any number of tasks evolves into this way,

 

public class MathDemo1 {         public static void main(String[] args) {         for(int i=0;i<100;i++){         System.out.println(getRandom(200,300));         }}         public static int getRandom(int start,int end){        int number = (int) (Math.random() * (end-start+1)) + start;return number;         }}

OK.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.