Java Math.abs 随机与 nextInt()

标签 java random

在 Java 中创建随机数生成器 - 查看 num1 和 num2,在哪些情况下我会使用这些方法中的任何一种来创建 1 到 8 之间的随机数?一种比另一种更有效,还有其他好处吗?

import java.util.*;

public class Chpt3 {
  public static void main(String[] args) {
    Random rand = new Random();
    int num1 = Math.abs(rand.nextInt()) % 8 + 1;
    int num2 = rand.nextInt(8) + 1;
    System.out.println(num1);
    System.out.println(num2);

  }
}

最佳答案

nextInt(n)0n-1 之间返回。

所以要在 1 到 8 之间,

int num2 = rand.nextInt(8) + 1;

这意味着您的第二个就是您需要的那个。


更新:

Math.abs(Integer.MIN_VALUE) 返回负值。

根据 this answer所以:

Integer.MIN_VALUE is -2147483648, but the highest value a 32 bit integer can contain is +2147483647. Attempting to represent +2147483648 in a 32 bit int will effectively "roll over" to -2147483648. This is because, when using signed integers, the two's complement binary representations of +2147483648 and -2147483648 are identical. This is not a problem, however, as +2147483648 is considered out of range.

For a little more reading on this matter, you might want to check out the Wikipedia article on Two's complement.

第一种方法只包含一个罕见的极端情况。这就是为什么最好使用第二个,因为它是安全的。

关于Java Math.abs 随机与 nextInt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176165/

相关文章:

java - Hibernate配置问题

java - 仍然无法在代理 servlet 中处理 HTTPS 请求

java - Eclipse 将不在工作区中的项目的文件保存在哪里?

java - 使用正则表达式提取日志 - java?

java - 从有序的 ArrayList 中挑选一个随机元素

java - 使用 Mastermind 和 Random() 类上的 Mocks 进行单元测试

java - 将文本文件输入到数组中,将文本文件中的数据随机化到数组中,将随机数据输出到单独的文本文件中

java - 什么是存储整数对的 O(1) 搜索内存高效数据结构?

c - 生成随机投票号码

java - 将java随机数生成偏向某个数字