import java.awt.Color; import java.awt.Graphics; import java.awt.Dimension; import java.awt.Polygon; public class Graph { private double xMin; private double xMax; private double yMin; private double yMax; private Color theColor; private Dimension theSize; private Polygon thePoints; public Graph(String fName, Parser parser, double x1, double x2, double y1, double y2, Color c, Dimension d) { initGraph(x1, x2, y1, y2, c, d); parser.define(fName); parser.parse(); int ixMax = theSize.width; int iyMax = theSize.height; int iSteps = theSize.width; double deltaX = (xMax - xMin) / iSteps; double x; double y; int iy; thePoints = new Polygon(); for (int i=0; i <= iSteps; i++) { x = xMin + i * deltaX; parser.setVariable("x",x); y = parser.evaluate(); if (y > yMax) iy = -1; else if (y < yMin) iy = theSize.height + 1; else iy = toScreen(y,iyMax,yMax, yMin); thePoints.addPoint(i,iy); } } public Graph(String fName, Parser parser, double x1, double x2, double y1, double y2, int sumStart, int sumEnd, Color c, Dimension d) { initGraph(x1, x2, y1, y2, c, d); parser.define(fName); parser.parse(); int ixMax = theSize.width; int iyMax = theSize.height; int iSteps = theSize.width; double deltaX = (xMax - xMin) / iSteps; double x, y; int iy; thePoints = new Polygon(); for (int i=0; i <= iSteps; i++) { x = xMin + i * deltaX; parser.setVariable("x",x); y = 0; for (int isum=sumStart; isum <= sumEnd; isum++) { parser.setVariable(2,isum); y += parser.evaluate(); } if (y > yMax) iy = -1; else if (y < yMin) iy = theSize.height + 1; else iy = toScreen(y,iyMax,yMax, yMin); thePoints.addPoint(i,iy); } } private void initGraph(double x1, double x2, double y1, double y2, Color c, Dimension d) { xMin = x1; xMax = x2; yMin = y1; yMax = y2; theColor = c; theSize = d; } public void drawAxis(Graphics g, Color c) { int ix0 = toScreen(0.0, theSize.width, xMin, xMax); int iy0 = toScreen(0.0, theSize.height, yMax, yMin); g.setColor(c); g.drawLine(ix0, 0, ix0, theSize.height); g.drawLine(0, iy0, theSize.width, iy0); } public void drawGraph(Graphics g) { g.setColor(theColor); g.drawPolygon(thePoints); } private int toScreen(double x, int iMax, double min, double max) { return (int)Math.round( iMax / (max - min) * (x - max) + iMax); } }