math.random always give 0 result

前端 未结 8 802
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 16:40

I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I\'m using Sublime Text. Here is the code

相关标签:
8条回答
  • 2021-01-29 17:24

    Read the doc :

    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0

    Therefore, you will always get less than 1, and the cast to int will round it down to 0. Use, for example, a Random object which has a nextInt(int max) method :

    Random rd = new Random();
    int number1 = rd.nextInt(10);
    int number2 = rd.nextInt(10);
    
    0 讨论(0)
  • Math.random() returns a number greater or equal than 0 and less than 1. What you are looking for is either

     int number1 = (int)(Math.random()*10);
     int number2 = (int)(Math.random()*10);
    

    or

     Random rand = new Random();
     int number1 = rand.nextInt(10);
     int number2 = rand.nextInt(10);
    

    Also, to get random number from given range, use this for Math.random()

    int number 3 = min + (int)(Math.random() * ((max - min) + 1))
    

    and for random.nextInt()

    int number 4 = random.nextInt(max - min) + min;
    
    0 讨论(0)
提交回复
热议问题