4 Replies - 181 Views - Last Post: 02 February 2016 - 09:44 AM Rate Topic: -----

#1 getmegetme26  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 13
  • Joined: 04-October 15

Help with random number?

Posted 02 February 2016 - 08:16 AM

hi i am trying out random numbers but stuck on something, please can someone help?

i have got a simple program that gives out random names, when i try to output several at the same time they come out the same. can i change it?

package NameGen;

public class NameGen1 {
	public static void main(String args[]) {
		String[]names;
		names = new String[10];
		names[0] = "ben";
		names[1] = "john";
		names[2] = "chris";
		names[3] = "matt";
		names[4] = "jack";
		names[5] = "alex";
		names[6] = "patric";
		names[7] = "sam";
		names[8] = "mike";
		names[9] = "andy";
		
		int num = (int) (Math.random()*10);
		
		System.out.println("My name is " + names[num]);
		System.out.println("My name is " + names[num]);
		System.out.println("My name is " + names[num]);
		System.out.println("My name is " + names[num]);
	}

}



My name is alex
My name is alex
My name is alex
My name is alex

Is This A Good Question/Topic? 0
  • +

Replies To: Help with random number?

#2 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 11137
  • View blog
  • Posts: 43,878
  • Joined: 12-June 08

Re: Help with random number?

Posted 02 February 2016 - 08:18 AM

I would think that if variable 'num' never changes but once you would keep using the same index.
Was This Post Helpful? 0
  • +
  • -

#3 getmegetme26  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 13
  • Joined: 04-October 15

Re: Help with random number?

Posted 02 February 2016 - 08:38 AM

any ideas guys ?
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 11137
  • View blog
  • Posts: 43,878
  • Joined: 12-June 08

Re: Help with random number?

Posted 02 February 2016 - 09:06 AM

'num' never changes. If you want it different then call the random before you want to use it.
Was This Post Helpful? 0
  • +
  • -

#5 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3169
  • View blog
  • Posts: 13,790
  • Joined: 20-September 08

Re: Help with random number?

Posted 02 February 2016 - 09:44 AM

Use a loop. Call Math.random in the loop

This post has been edited by g00se: 02 February 2016 - 09:45 AM
Reason for edit:: Clarification

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1