bramming
April 27th, 2009, 07:45 PM
Hey :) i finally decided to start doing some tutorials on programming, and chose java for a start with the Eclipse IDE. I understand all i have read so far in the http://www.linuxbog.dk/java/java/index.html tutorials (sorry it's in danish so you will probably not understand anything it says). Theres one thing that really wonders me though.
There's an example of a program throwing a dice and then displaying the value of the toss in a terminal. To calculate the side it hits the following code is used:
public class Terning
{
// the current side facing upwards
int værdi;
// constructor
public Terning()
{
kast(); // call kast() that sets the value to something reasonable
}
// method to throw the dice
public void kast()
{
// find a random side
double tilfældigtTal = Math.random();
værdi = (int) (tilfældigtTal * 6 + 1);
}
// gives a description of the dice
public String toString()
{
String svar = ""+værdi; // value as string
return svar;
}
}
What i dont understand, is that to calculate the side, its using Math.random() * 6 + 1.
As far as i can see Math.random() gives a random double between 0.1 and 1.0. So lets say it gives 1.0 it would mean the side would be 6*1+1 = 7? when i run it, it always returns between 1 and 6 as its supposed to, and if i remove the +1 it only goes up to 5. But how can 1.0*6 give max 5? :S I hope my question is understandable as well as the code ;)
Thanks in advance :)
There's an example of a program throwing a dice and then displaying the value of the toss in a terminal. To calculate the side it hits the following code is used:
public class Terning
{
// the current side facing upwards
int værdi;
// constructor
public Terning()
{
kast(); // call kast() that sets the value to something reasonable
}
// method to throw the dice
public void kast()
{
// find a random side
double tilfældigtTal = Math.random();
værdi = (int) (tilfældigtTal * 6 + 1);
}
// gives a description of the dice
public String toString()
{
String svar = ""+værdi; // value as string
return svar;
}
}
What i dont understand, is that to calculate the side, its using Math.random() * 6 + 1.
As far as i can see Math.random() gives a random double between 0.1 and 1.0. So lets say it gives 1.0 it would mean the side would be 6*1+1 = 7? when i run it, it always returns between 1 and 6 as its supposed to, and if i remove the +1 it only goes up to 5. But how can 1.0*6 give max 5? :S I hope my question is understandable as well as the code ;)
Thanks in advance :)