Simple Function Graph

<< Temp Converter | LabTrailIndex | GameStateLab >>

Here we can define a simple function

public class Function 
    public Function()

    public double of(double x){
    	     return .2*(Math.pow(x,3)+ x*x -17.0*x +15.0);

And a simple Applet that scales a graph from -10 to 10 in both directions to a 600 x 400 rectangle, with info on the location of the mouse

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class SimpleFunctionGraph extends Applet implements MouseMotionListener
	private Function f;
	public static final int WIDTH=600;
	public static final int HEIGHT=400;
	public static final double X_MIN=-10;
	public static final double X_MAX=10;
	public static final double Y_MIN=-10;
	public static final double Y_MAX=10;
	private double xCoord,yCoord;
	public void init()
		f = new Function();
	public void paint(Graphics g)
		g.fillRect(0,0,WIDTH, HEIGHT);
		int x1=screenX(X_MIN);int y1=screenY(0);
		int x2=screenX(X_MAX); int y2=screenY(0);
		g.drawLine(x1, y1, x2, y2);
		g.drawLine(x1, y1, x2, y2);
		for (double x=X_MIN; x<X_MAX; x+=.1){

                        // your code here 

			g.drawLine(x1, y1, x2, y2);
		g.drawString("x:"+xCoord, 20, 20);
		g.drawString("y:"+yCoord, 20, 40);

	private int screenY(double y) {
		double p=(y-Y_MIN)/(Y_MAX-Y_MIN);
		return (int)(HEIGHT-p*HEIGHT);
	private int screenX(double x) {
		double p=(x-X_MIN)/(X_MAX-X_MIN);
		return (int)(p*WIDTH);
	public void mouseDragged(MouseEvent e) {	}
	public void mouseMoved(MouseEvent e) {
		xCoord= X_MIN+e.getX()*(X_MAX-X_MIN)/(WIDTH);
		yCoord= Y_MAX-e.getY()*(Y_MAX-Y_MIN)/(HEIGHT);


See if you can add the for loop to draw the function using a double x and the f.of(x) method.