Java中取某一个范围的随机数

来源:互联网 发布:微信封面设计软件 编辑:程序博客网 时间:2024/04/16 11:32
一、取模操作
public static void main(String[] args)
{
for (int i = 1; i <= 20; i++)
{
int j = i % 11;
System.out.println(i + "%11的结果——" + j);
}
}
1%11的结果——1
2%11的结果——2
3%11的结果——3
4%11的结果——4
5%11的结果——5
6%11的结果——6
7%11的结果——7
8%11的结果——8
9%11的结果——9
10%11的结果——10
11%11的结果——0
12%11的结果——1
13%11的结果——2
14%11的结果——3
15%11的结果——4
16%11的结果——5
17%11的结果——6
18%11的结果——7
19%11的结果——8
20%11的结果——9

二、java.uitl.Random
random.nextInt(20),任意取[0,20)之间整数,其中0可以取到,20取不到

三、取某个范围的任意数
public static String getRandom(int min, int max)
{
Random random = new Random();
int s = random.nextInt(max) % (max - min + 1) + min;
return String.valueOf(s);

}


原创粉丝点击