输入一个数,生成一个1与这个数范围的随机数,返回值为int
新手不知道写的对不对,求大神指点
以下是代码:
public static void main(String[] args){
index(50);
}
public static Integer index(Integer max){
if(max instanceof Integer&&max!=null){
Random random = new Random();
Integer s = random.nextInt(max)%(max+1);
System.out.println("随机数为==>"+s);
return s;
}else{
return 0;
}
}
random

解决方案 »

  1.   

    import java.io.IOException;
    import java.util.Random;public class Hello {
        public static int nextInt(int n) {
            Random rand = new Random(System.nanoTime());
            return rand.nextInt(n) + 1;
        }    public static void main(String[] args) throws IOException {
            System.out.println(nextInt(10));
        }
    }
      

  2.   

    (int) (Math.random() * n) + 1
      

  3.   

    int x=random.nextInt(n)生成的是0<=x<n,你最后加1就是了。