There's something wrong with this code and not to sure what, I'm trying to make a random number between 0.8 and 1.2, this can then be used to times the length of the branches that are made using this program.
import java.awt.*;
import javax.swing.*;
import java.util.Random;
public class OneFractalTree extends JApplet {
final double ONE_DEGREE = Math.PI/180;
final double BRANCHANGLE = ONE_DEGREE*30;
final double SHRINKFACTOR = .65;
final int START_LENGTH = 75;
//Draws branches
public void drawbranch( Graphics g,
double startx, //coordinates of branch start
double starty,
double length, //length of branch
double angle ) //angle of branch
{
double endx = startx + Math.sin(angle) * length; //Calculates the end coordinates of the branch
double endy = starty + Math.cos(angle) * length;
/**
* The loop draws the branches and continues until the length becomes too small
* i.e. when length is less than 1, length becomes smaller by shrinkfacter every iteration)
*/
if( 1 < length ) {
Random rand = new Random();
int randomNum = rand.nextInt((12 - 8) + 1) + 1;
double randomNumdouble = randomNum / 10;
g.setColor( length < 5 ? Color.green : Color.black ); //Sets color according to length
g.drawLine( (int)startx, (int)starty, (int)endx, (int)endy ); //Coordinates to draw line
drawbranch( g, endx, endy, (length * SHRINKFACTOR) * randomNumdouble, angle - BRANCHANGLE ); //1st branch creation
drawbranch( g, endx, endy, (length * SHRINKFACTOR) * randomNumdouble, angle + BRANCHANGLE ); //2nd branch creation
drawbranch( g, endx, endy, (length * SHRINKFACTOR) * randomNumdouble, angle); //3rd branch creation
}
}
public void paint( Graphics g ) {
Rectangle r = getBounds(); //Finds height of applet viewer
drawbranch( g, r.width/2, r.height, START_LENGTH, Math.PI ); //Calls method to draw branch
}
}
The correct formula is
Random.nextDouble() * (max - min) + min;
But to fix your code:
int randomNum = rand.nextInt((12 - 8) + 1) + 1;
double randomNumdouble = randomNum / 10.0; // 10 will be interpreted as an `int`, whereas 10.0 will be a `double`