How do you use math.random to generate random ints?

后端 未结 7 854
情话喂你
情话喂你 2020-12-06 01:23

How do you use Math.random to generate random ints?

My code is:

int abc= (Math.random()*100);
System.out.println(abc);

All it print

相关标签:
7条回答
  • 2020-12-06 01:35
    int abc= (Math.random()*100);//  wrong 
    

    you wil get below error message

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int

    int abc= (int) (Math.random()*100);// add "(int)" data type
    

    ,known as type casting

    if the true result is

    int abc= (int) (Math.random()*1)=0.027475
    

    Then you will get output as "0" because it is a integer data type.

    int abc= (int) (Math.random()*100)=0.02745
    

    output:2 because (100*0.02745=2.7456...etc)

    0 讨论(0)
  • 2020-12-06 01:38

    Cast abc to an integer.

    (int)(Math.random()*100);
    
    0 讨论(0)
  • 2020-12-06 01:40

    As an alternative, if there's not a specific reason to use Math.random(), use Random.nextInt():

    import java.util.Random;
    
    Random rnd = new Random();
    int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.
    
    0 讨论(0)
  • 2020-12-06 01:41
    double  i = 2+Math.random()*100;
    int j = (int)i;
    System.out.print(j);
    
    0 讨论(0)
  • 2020-12-06 01:42

    For your code to compile you need to cast the result to an int.

    int abc = (int) (Math.random() * 100);
    

    However, if you instead use the java.util.Random class it has built in method for you

    Random random = new Random();
    int abc = random.nextInt(100);
    
    0 讨论(0)
  • 2020-12-06 01:45

    you are importing java.util package. That's why its giving error. there is a random() in java.util package too. Please remove the import statement importing java.util package. then your program will use random() method for java.lang by default and then your program will work. remember to cast it i.e

    int x = (int)(Math.random()*100);
    
    0 讨论(0)
提交回复
热议问题