the number b included, and how to enable a - I can not figure it out

import java.util.Random; public class RandomNumberMethod { public int c; public int randomNumber (int a,int b){ Random random = new Random(); if (b>a) { c = random.nextInt(b - a) + a+1; }else{ if (b<a) { c = random.nextInt(a - b) + b+1; }else{ c=a; } } return c; } } 

    1 answer 1

    The random.nextInt(int n) method returns a number from 0 to n-1. Therefore, you need to transfer n + 1 to it (i.e., increase the upper bound by 1 BEFORE the transfer to the method) to get a number from the range from 0 to n (= (n+1)-1 ) inclusive:

     public int randomNumber (int a, int b){ int c; Random random = new Random(); if (b>a) { b = b + 1; c = random.nextInt(b - a) + a; }else{ if (b<a) { a = a + 1; c = random.nextInt(a - b) + b; }else{ c=a; } } return c; }