Hi

I have searched this site for help with this and used an example of a lottery numbers program.

However, I need to modify it slightly but can't seem to get it right.

I would like to be able to generate random numbers between 0 and 100 (maybe negative oness as well). The code below just generates 7 numbers between 0 and 6 and I can't see where I need to adjust the code. If anyone could help me with this, I would be really grateful, even just an explaination so I can work it out myself would be great as I just can't see where it is saying only use those low 0 - 6 digits! :rolleyes:

// random number generator

import java.lang.Math;
// setting up array with random numbers 26 july 2005

public class myRandomNodes {
    public static void main(String[] args)
    {
     new ranNumbers (7);    
    }
}

class myRanNumbers {
    private int[] numbers;

  public myRanNumbers (int n )
  {
    numbers = new int[n];

    // initialise numbers
    int i = 0;

    while (i < n ) {
        //int r = (int) (Math.random() * n);
//       create a random integer between 1 and 100 inclusive
              int r = (int) Math.floor(Math.random() * 100);

        if (add (numbers, i, r)) {
            ++i;
        }
    }

    show_all (numbers);
  }

  private boolean add (int [] list, int size, int val)
  {
    for (int i = 0; i < size; i++ ){
        if (list[i] == val) {
            return false;
        }
    }
  list[size] = val;

  return true;
  }

  private void show_all (int[] list)
  {
    for (int i = 0; i < list.length; i++ ) {
        //System.out.print(list[i] + " ");
        System.out.println("rounded number between 0 and 100 is ");

    }
    System.out.println();
    }
  }

Dani AI

Generated

Short answer: you were multiplying by the array-size (n) so the generated values were in 0..n-1 (with n==7 that gives 0..6). Math.random() returns a value in [0.0, 1.0) and casting to int drops the fractional part, so the multiplier determines the top of the range.

A safe, general rule (using Math.random) to get an integer between min and max inclusive:

int r = min + (int)(Math.random() * (max - min + 1));

Notes: the +1 makes the upper bound inclusive; if you want negatives just set min negative. As pointed out, java.util.Random (or ThreadLocalRandom) is an alternative — use a positive bound and add the shift (min).

If you need unique random values, prefer generating the full pool and sampling from it (no looping retries) or check the range size first. Example approach (keeps order random, guarantees uniqueness, avoids infinite loops):

import java.util.*;
import java.util.stream.*;

int min = 0, max = 100, n = 7;
List<Integer> pool = IntStream.rangeClosed(min, max).boxed().collect(Collectors.toList());
Collections.shuffle(pool);
int[] numbers = pool.stream().limit(n).mapToInt(Integer::intValue).toArray();

for (int v : numbers) System.out.println(v);

Cautions and tips:

  • Always verify n <= (max - min + 1) before trying to produce unique numbers.
  • Your add(...) approach works but can spin forever when the requested count exceeds available unique values.
  • Follow ’s advice on naming and formatting: use PascalCase for class names, consistent indentation, and meaningful method names — it makes debugging and reasoning about bounds much easier.

This addresses the 0..6 surprise, how to change the range (including negative ranges), and a robust way to get unique samples without retry loops.

Recommended Answers

All 5 Replies

1) use code tags
2) follow the Sun coding standards, which you can get from Sun.

Doing both will make your code a lot easier to read and debug, as it stands I'm not even going to try.

// random number generator

import java.lang.Math;


public class myRandomNodes 
{
   public static void main(String[] args)
   {
     new ranNumbers (7); 
   }
}

  class myRanNumbers 
  {
    private int[] numbers;

    public myRanNumbers (int n )
    {
      numbers = new int[n];

      // initialise numbers
      int i = 0;

      while (i < n ) 
      {
        int r = (int) Math.floor(Math.random() * 100);
        if (add (numbers, i, r)) 
        {
          ++i;
        }
      }

     show_all (numbers);
   }

   private boolean add (int [] list, int size, int val)
   {
     for (int i = 0; i < size; i++ )
     {
       if (list[i] == val) 
       {
         return false;
       }
     }
   list[size] = val;
 
   return true;
   }

   private void show_all (int[] list)
   {
     for (int i = 0; i < list.length; i++ ) 
     {
     System.out.print(list[i] + " ");
     }
     System.out.println();
     }
  }

Hope it makes it a bit easier to read - sorry about the unformatting before :-|

Use the Random Class. It's more random than Math.random();

import java.util.*;

public class RandomClassTest
{
	public static void main(String[] args)
	{
		Random randNumGenerator = new Random();

		int[] x = new int[7];
		for (int i=0; i<x.length; i++)
		{
			x[i] = (randNumGenerator.nextInt(100)+1);
		}
	}
}

Be sure to add 1 if you want to reach 100.

Hi everyone,

Use the Random Class. It's more random than Math.random();

import java.util.*;

public class RandomClassTest
{
	public static void main(String[] args)
	{
		Random randNumGenerator = new Random();

		int[] x = new int[7];
		for (int i=0; i<x.length; i++)
		{
			x[i] = (randNumGenerator.nextInt(100)+1);
		}
	}
}

Be sure to add 1 if you want to reach 100.

Could not have said it better myself

Richard West

Hi

Thanks very much for the response - appreciate it. :mrgreen:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.