java - Method returns 0 -


i've made program generates random number every time gives 0.0

program:

import java.util.*;  public class randomnumber {      public static void main(string args[]){          double quantitycolors = 5;         double mastermind = 0;          random(quantitycolors, mastermind);         system.out.println(mastermind);     }      public static double random(double quantitycolors, double mastermind){          mastermind = math.random();         mastermind = mastermind * quantitycolors;         mastermind = (int) mastermind;          return mastermind ;     } } 

i've been searching problem is, problem in return.

first of all, can use builtin function generate next integer upper bound: random.nextint(int). instance:

random rand = new random(); int mastermind = rand.nextint(quantitycolors); 

instead of writing random method yourself.

it better use builtins since these have been tested extensively, implemented rather fast, etc.

next seem assume java uses pass-by-reference. if perform following call:

random(quantitycolors, mastermind); 

java make copy of value of mastermind. setting parameter in method has no use. way set value - not encapsulated in object - returning value. so:

mastermind = random(quantitycolors, mastermind); 

to make long story short: method not return 0, don't useful it.

a better solution drop random method , use:

import java.util.*;  public class randomnumber {      public static void main(string args[]){          int quantitycolors = 5;         random rand = new random();          int mastermind = rand.nextint(quantitycolors);         system.out.println(mastermind);     } } 

further remarks

in random method:

public static double random(double quantitycolors, double mastermind){ 

the mastermind parameter rather useless since set value, better remove , use local variable instead.

furthermore java standards name of classes, interfaces, etc. start uppercase; names of methods , variables lowercase.

finally unclear why use doubles since values calculate integral.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -