Help rewrite this code to generate random numbers in the range from -20 to 20

System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ Ρ€Π°Π·ΠΌΠ΅Ρ€ массива: "); Scanner in = new Scanner(System.in); Random r=new Random(System.currentTimeMillis()); n = in.nextInt(); arr = new int [n]; for (int i=0;i<arr.length;i++) arr[i] = (int) ( Math.random()* n); for (int i: arr) 

    2 answers 2

     Random mRand = new Random(); int countRandom = 10; int arr[] = new int [countRandom]; for (int i = 0; i < arr.length; i++) { Log.i("LOG_TAG", "int random - " + getRandomInt(-20, 20)); } //Π²Ρ‹Π²ΠΎΠ΄ случайного Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΌΠ΅ΠΆΠ΄Ρƒ ΠΌΠΈΠ½ ΠΈ макс (Java) private int getRandomInt(int min, int max){ return mRand.nextInt(max - min + 1) + min; } 

    Possible without array

     int countRandom = 10; for (int i = 0; i < countRandom; i++) { Log.i("LOG_TAG", "int random - " + getRandomInt(-20, 20)); } 
    • one
      +1, but why in your code array? And I would not create Random at each iteration. - VladD
    • @VladD well yes (:, really. Random render, remove array. - TimurVI

    You can try Random (System.currentTimeMillis ()% 41 - 20); Thus, we will have balances from 0 to 40, then subtract 20, it will turn out from -20, to 20.

    • 3
      Try it and add the resulting block of code. - 0xdb