Here you can find the source of randomInteger(int low, int high)
low
and less than or equal to high
.low
limit is inclusive and high
limit is also inclusive.randomInteger = (int) (Math.random() * (high + 1 - low)) + low; (low: Inclusive, high: Inclusive)
Parameter | Description |
---|---|
low | The low limit of the result (inclusive). |
high | The high limit of the result (inclusive). |
public static int randomInteger(int low, int high)
//package com.java2s; /**/*from w w w .j a va2 s. c o m*/ * Project: JavaGE Library * Author: Loukas Georgiou * Date: 14 Jan 2006 * * Copyright 2006, 2008 Loukas Georgiou. * This file is part of JavaGE (jGE) Library. * * jGE Library is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * jGE Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with jGE Library. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * Returns an integer value with a positive sign, greater than or equal to <code>low</code> * and less than or equal to <code>high</code>.<br> * Note: <code>low</code> limit is inclusive and <code>high</code> limit is also inclusive.<br> * The formula used in this method is:<br> * <code>randomInteger = (int) (Math.random() * (high + 1 - low)) + low; (low: Inclusive, high: Inclusive)</code> * * @param low The low limit of the result (inclusive). * @param high The high limit of the result (inclusive). * @return The random number in the given range. */ public static int randomInteger(int low, int high) { return (int) (Math.random() * (high + 1 - low)) + low; } }