program wont compile...


V

vtcompsci

i was trying to get some bugs out of my program but i cant get it to
compile... i get some horrable errors with PathDisplay.java


/**
* This class controls a simulation of two particles in motion.
* It creates the particles, sets their initial and final positions
* and tracks them through their motion. When the simulation has
* completed, the paths of the two particles are displayed on a graphical
* display.
*
*
*/
public class Simulator {

Vector2d [] position1, position2;
int numsteps = 100;
float timestep;
float launchangle;

Particle object1, object2;

/**
* Constructor. Sets the time stepping interval for the integration
* of the equations of motion. We require 100 time steps be taken in
* the time it takes the second object (object2) to fall to the ground.
*
*/
public Simulator() {
// Compute the control parameters for the simulation. We want
// to track for 100 time steps, using the amount of time that
// the vertically falling object is above the ground. We may
// exit before this, but we won't exit after this.
// (This simulation assumes that the second particle begins
// at rest at a height of 10.0 m)
float time;
time = (float)Math.sqrt(2.0 * 10.0 / 9.8);
// was commented out and needs to be uncommented
// //timestep = time/numsteps;
timestep = time/numsteps;
}


/**
* Main program for the simulation.
* @param args the angle at which the first projectile is
* launched. This argument is optional - if not given, the
* program defaults to 45 degrees.
*/
public static void main(String[] args) {

Simulator mysim = new Simulator();

// The command line, if it contains any arguments, should contain
// the angle at which to launch particle 1.
float angle = (float)Math.atan(1.0);
if (args.length >= 0) {
angle = (float)(Float.parseFloat(args[0]) * 4.0 * Math.atan(1.0) /
180.0 );
}
mysim.setAngle(angle);
mysim.generateParticles();
// bug needs to be runSimulation
mysim.runSimulation(true);

}

/**
* runSimulation is the main control for the simulation. It
* determines what accelerations will be applied (in this case,
* a constant acceleration of 9.8 m/s/s downward), keeps track
* of the path that each object follows, and steps the objects
* through their motion. When the motion is complete, the paths
* are displayed.
*
*/

//public void runSimulation() {
public void runSimulation(boolean objectsCollided) {
// We're performing this simulation near the surface of the earth
Vector2d acceleration = new Vector2d(0, -9.8);
// boolean objects collided needs to be a parameter
// boolean objectsCollided = false
objectsCollided = false;

position1 = new Vector2d[numsteps];
position2 = new Vector2d[numsteps];

int actualsteps = 0;
for (int i=0; i < numsteps; i++) {
actualsteps++;
position1 = object1.position();
position2 = object2.position();

// We can break on a collision. If a collision
// does not occur, we take a maximum of 100 time
// steps.
if (object1.collidesWith(object2)) {
objectsCollided = true;
break;
}

// The objects stop updating once they hit the
// ground.
if (object1.position().Y() >= 0)
object1.updateParticle(acceleration,timestep);
if (object2.position().Y() >= 0)
object2.updateParticle(acceleration,timestep);
}

// Allocate new vectors for the positions, copy the results
// over (to make sure that the lengths are the same). This
// is needed because a collision can end the loop early which
// will leave a bunch of null slots in the position arrays.
Vector2d [] a1, a2;
a1 = new Vector2d[actualsteps];
a2 = new Vector2d[actualsteps];
//no ; needed after the for loop
//for (int i=0; i<actualsteps; i++); {
for (int i=0; i<actualsteps; i++) {
a1 = position1;
a2 = position2;
}
position1 = a1;
position2 = a2;

// Display the resutls
PathDisplay pd = new PathDisplay();
pd.show();
// does not have a method call for draw
pd.draw(position1, position2, true);
}

/**
* Nothing mysterious here. It sets the launch angle variable
* to the value given by the user.
* @param angle the angle given on the command line.
*/
public void setAngle(float angle) {
launchangle = angle;
}

/**
* We allocate and initialize the position and velocity of the
* two objects. Object 1 starts at the origin, and is launched at
* an angle. Object 2 starts 10m away and 10m up in the air. It
* simply falls straight down.
*
*/
public void generateParticles() {

// Compute the initial position and launch velocity of the first
// object. This object begins at the origin and is launched with
// a speed of 5 m/s in the direction specified by the angle parameter
// passed in on the command line. This object will have a radius of
// 0.05 m.
Vector2d pos, vel;
pos = new Vector2d(0,0);
vel = new Vector2d(12.0 * Math.cos(launchangle),
12.0 * Math.sin(launchangle));
object1 = new Particle(pos, vel, 0.05f);

// Compute the initial position and launch velocity of the second
// object. This object begins at an x location of 10 m, and a y
// location of 10 m. It begins falling from rest. This object will
have
// a radius of 0.05 m.
pos = new Vector2d(10.0,10.0);
vel = new Vector2d(0.0, 0.0);
object2 = new Particle(pos, vel, 0.05f);
}

}






/**
* PathDisplay.java
* Display the paths of two particles as given by the two input
* vectors to the <i>Draw(v1,v2,hitflag)</i> function.
*
*/

import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import javax.swing.*;


/**
* The PathDisplay class creates a display window which will show
* the path taken by the two objects and provide a "Quit" button
* to exit the program.
* @author jhardie
*
*/
public class PathDisplay {

JFrame frame;
Container content;
PathGraph component;
JButton button;

/**
* PathDisplay()
* This constructor creates a basic GUI frame and adds three objects
* to it. The first is a JComponent derived class which will manage
* the plotting area. The second is a JPanel which will resize with
the
* window. The third is a JButton which allows you to quit the
application.
*/
PathDisplay() {

// Allocate the enclosing window frame
frame = new JFrame("Path Display");

// Get the content pane of the window and add a layout
// manager to it.
content = frame.getContentPane();
content.setLayout(new BorderLayout());

// Allocate the component which is where we'll draw the graph.
component = new PathGraph();

// Allocate the "Quit" button. We will need a panel to hold it
// so that the button doesn't become huge.
button = new JButton("Quit");
JPanel jp = new JPanel();

// When the button is clicked, we want to quit the application.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
System.exit(0);
}
});

// put the button in the panel.
jp.add(button);

// Add the graph component and the button panel to the window
// frame.
content.add(component, BorderLayout.CENTER);
content.add(jp, BorderLayout.SOUTH);

// Set the size of the enclosing window.
frame.setSize(300,300);

// When the close button on the window pane is clicked we will
// quit the application also. (Note: this is NOT the same thing
// as clicking the quit button).
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

/**
* show()
* Makes the constructed frame visible. Causes a redraw.
*/
public void show() {
frame.setVisible(true);

}

/**
* hide()
* Makes the constructed frame invisible.
*/
public void hide() {
frame.setVisible(false);
}

/**
* Draw the two paths. This function will draw the two paths
* stored in the vectors v1 and v2. It assumes (implicitly) that
* v1 and v2 are the same size.
* @param v1 the first path to draw
* @param v2 the second path to draw
* @param hitflag true if the objects collide, false otherwise.
*/
public void draw(Vector2d [] v1, Vector2d [] v2, boolean hitflag) {
component.markHit(hitflag);
component.drawPaths(v1,v2);
frame.repaint();
}

/**
* Simple test program for the PathDisplay class.
* @param args Command line arguments (ignored)
*/
public static void main(String[] args) {
PathDisplay d = new PathDisplay();

// Allocate two vectors
Vector2d [] v1, v2;
v1 = new Vector2d[21];
v2 = new Vector2d[21];

// Fill them.
for (int i=0; i<21; i++) {
v1 = new Vector2d();
v2 = new Vector2d();
v1.X((float)(0.1*i));
v1.Y((float) (v1.X()*v1.X() + 1.0));
v2.X((float)(0.1*i));
v2.Y((float)(4.0 - v2.X()*v2.X()));
}
// Display the results.
d.show();
d.draw(v1,v2,false);
}
}


/**
* The PathGraph class handles the actual drawing of the paths
* on the image area of the display. To do so, it determines
* the limits of the data, maps this onto the pixel ranges and
* orientation of the image area, and draws the paths.
*/
class PathGraph extends JPanel {

// Necessary because JComponent is serializable. Ignored
// in this program.
static final long serialVersionUID = 0;

// The ranges of the data on the x and y axes.
private float xmin, xmax, ymin, ymax;

// Pixel values used to determine the positioning of objects
// in the display.
private int axisleft,axisright,axistop,axisbottom;
private int xlabeloffset, ylabeloffset;

// Scale factors to map the data range onto the pixel range
// for plotting.
float xscale, yscale;

// The image is where the data is drawn, the paper object contains
// the tools for efficient drawing.
Graphics2D paper;

// For convenience, we keep track of the data that was passed in
// so that we can handle any resize/repaint commands gracefully.
// (Note: This is NOT a good idea in general)
Vector2d [] v1 = null, v2 = null;
boolean hit = false;

/**
* This internal class is used to respond to window resizing
* events.
*/
class myComponentAdapter extends ComponentAdapter {
public void componentResized(ComponentEvent e) {
paper = null;
repaint();
}
public void componentShown(ComponentEvent e) {
repaint();
}
}

/**
* Constructor. Simple initialization of some of the member
variables.
*
*/
PathGraph() {
paper = null;
xmin = ymin = 0;
xmax = ymax = 1;

// Add an action listener to handle resize events
addComponentListener(new myComponentAdapter());
}

/**
* Compute the pixel position of the given data point.
* @param x the data point to be converted
* @return the pixel position on the screen.
*/
private int scaleX(float x) {
return (int)(xscale * (x-xmin) + axisleft);
}

/**
* Compute the y pixel position of the given data point.
* @param y The y component of the data point.
* @return The corresponding pixel position.
*/
private int scaleY(float y) {
return (int)(yscale * (ymax - y) + axistop);
}

/**
* Draw the paths given by the vector arrays. Assumes that the
* vectors v1 and v2 are the same size.
* @param v1 the first path
* @param v2 the second path
*/
public void drawPaths(Vector2d [] thisv1, Vector2d [] thisv2) {
if ((v1 == null) || (v1 != thisv1)) {
v1 = thisv1;
}
if ((v2 == null) || (v2 != thisv2)) {
v2 = thisv2;
}
if ((v1 == null) || (v2 == null))
{
xmin = ymin = 0;
xmax = ymax = 1;
return;
}
xmin = ymin = 1000000;
xmax = ymax = 0;
// Find the boundaries on the vectors.
for (int i=0; i<v1.length; i++) {
// This can be done more efficiently
if (xmin > v1.X())
xmin = v1.X();
if (xmin > v2.X())
xmin = v2.X();
if (xmax < v1.X())
xmax = v1.X();
if (xmax < v2.X())
xmax = v2.X();
if (ymin > v1.Y())
ymin = v1.Y();
if (ymin > v2.Y())
ymin = v2.Y();
if (ymax < v1.Y())
ymax = v1.Y();
if (ymax < v2.Y())
ymax = v2.Y();
}
return;
}

private void DisplayLines() {
// Now we know what the limits are, draw the box.
redrawGraph();

if ((v1 == null) || (v2 == null)) {
return;
}

// And finally, draw the line.
Color oldcolor = paper.getColor();
int prevx1, prevy1, prevx2, prevy2;
prevx1 = scaleX(v1[0].X());
prevy1 = scaleY(v1[0].Y());
prevx2 = scaleX(v2[0].X());
prevy2 = scaleY(v2[0].Y());
paper.setColor(Color.GREEN);
paper.fillOval(prevx1-2,prevy1-2,4,4);
paper.setColor(Color.BLUE);
paper.fillOval(prevx2-2,prevy2-2,4,4);
int x,y;
for (int i=1; i<v1.length; i++) {
// Draw the segment for the first line
x = scaleX(v1.X());
y = scaleY(v1.Y());
paper.setColor(Color.green);
paper.drawLine(prevx1,prevy1,x,y);
paper.fillOval(x-2,y-2,4,4);
prevx1 = x;
prevy1 = y;
x = scaleX(v2.X());
y = scaleY(v2.Y());
paper.setColor(Color.BLUE);
paper.drawLine(prevx2,prevy2,x,y);
paper.fillOval(x-2,y-2,4,4);
prevx2 = x;
prevy2 = y;
}
paper.setColor(oldcolor);
String message;
if (hit) {
message = "Hit";
int last = v2.length - 1;
paper.setColor(Color.RED);
x = scaleX(v2[last].X());
y = scaleY(v2[last].Y());
paper.fillOval(x-8,y-8,16,16);
paper.setColor(oldcolor);
}
else {
message = "Missed";
}

paper.drawString(message,axisleft+15,axistop+20);
}

/**
* Saves flag marking a collision so that it can be used when the
* picture is redrawn.
* @param hitflag true if there was a collision, false otherwise.
*/
public void markHit(boolean hitflag) {
hit = hitflag;
}

/**
* Callback function to handle redrawing the image when something in
* the system or display changes.
*/
// public void paint(Graphics g) {
public void paintComponent(Graphics g) {
super.paintComponent(g);
paper = (Graphics2D)g;
paper.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
clear();
DisplayLines();
}

/**
* Erases the current image.
*
*/
public void clear() {
paper.setPaint(Color.white);
paper.fillRect(0,0,getSize().width,getSize().height);
paper.setPaint(Color.black);
}


/**
* Determines the limits on the axes, then draws the axis labels,
* the axis lines, and computes the scale factors used by scaleX and
* scaleY functions.
*
*/
private void redrawGraph() {
// Fill image background with white.
paper.setPaint(Color.white);
paper.fillRect(0,0,getSize().width,getSize().height);

// Draw the axes NOTE: In a java image, by default, the
// origin of the plotting area is at the UPPER LEFT and has
// coordinates 0,0. This means that computations for plotting
// vertically must be reversed from the usual conventions for
// plotting graphs. We can easily take care of this with an
// affine transformation, but we'll use BFI (Brute Force and
// Ignorance) for now.
axisright = (int)(getSize().width * 0.95);
axisleft = (int)(axisright * 0.15);
axisbottom = (int)(getSize().height * 0.90);
axistop = (int)(getSize().height * 0.02);

xlabeloffset = 5;
ylabeloffset = 5;

paper.setPaint(Color.black);
paper.drawRect(axisleft,axistop,
axisright-axisleft,axisbottom-axistop);

// Label the limits of the axes. These should be centered
// so that the right hand side is close to the axis for the
// vertical labels, and so the font is below the axis with the
// left hand side lined up with the tic marks for the horizontal
// labels.
float x, y;
float dimension;
String label;

//***** NOTE: These should be moved to the same place that
// the image is constructed. No need to do them
// each time we redraw.

// We'll render in monospaced type, ten points high.
Font font = new Font("Monospaced",Font.PLAIN,10);

// To make adjustments, we need to get the font rendering
// graphics context - so we know how to translate the "theoretical"
// font to pixels on the screen.
paper.setFont(font);
FontRenderContext frc = paper.getFontRenderContext();

// The top label on the Y axis. First find out how wide the
// message is. This will give us an additional offset.
label = Double.toString(ymax);
dimension = (float)font.getStringBounds(label,frc).getWidth();

// Compute the coordinates of the text message.
x = axisleft - dimension - xlabeloffset;

// Shift this down so we don't clip the text.
y = axistop + (float)font.getStringBounds(label,frc).getHeight();

// Draw it!
paper.drawString(label,x,y);


// Same computation for the bottom label on Y
label = Double.toString(ymin);
dimension = (float)font.getStringBounds(label,frc).getWidth();
x = axisleft - dimension - xlabeloffset;
y = axisbottom;
paper.drawString(label,x,y);

// Now for the left label on the X axis.
label = Double.toString(xmin);
dimension = (float)font.getStringBounds(label,frc).getHeight();
x = axisleft;
y = axisbottom + dimension + ylabeloffset;
paper.drawString(label,x,y);

// Finally, the right label on the X axis. We need to do
// two offsets here so that the label doesn't extend past the
// right hand side of the image.
label = Double.toString(xmax);
dimension = (float)font.getStringBounds(label,frc).getHeight();
y = axisbottom + dimension + ylabeloffset;
dimension = (float)font.getStringBounds(label,frc).getWidth();
x = axisright - dimension;
paper.drawString(label,x,y);

// Set up a transformation to allow drawing only into the plot area.
xscale = (axisright-axisleft)/(xmax-xmin);
yscale = (axisbottom-axistop)/(ymax-ymin);
}
}






/**
* Vector2d.java
* Represents some operations on 2-D vectors for geometry and basic
* physics computations.
*
*/
class Vector2d {
private float x = 0, y = 0;

/**
* Default Constructor.
*
*/
public Vector2d() { x = 0; y = 0; }

/**
* Parameterized Constructor. Sets the member variables to
* the values passed in.
* @param xv The desired value of x
* @param yv The desired value of y
*/
public Vector2d(float xv, float yv) { x = xv; y = yv; }
public Vector2d(double xv, double yv) { x = (float)xv; y = (float)yv;
}

// Accessor/Settor functions.
public void X(float xv) { x = xv; }
public void Y(float yv) { y = yv; }
public float X() { return x; }
// needs to be return y not return x
// public float Y() { return x; }
public float Y() { return y; }

/**
* Add two vectors
* @param rhs the right hand side vector to be added
* @return a new vector, the sum of this + rhs.
*/
public Vector2d add(Vector2d rhs) {
return new Vector2d(x + rhs.x, y + rhs.y);
}

/**
* Subtract two vectors.
* @param rhs the right hand side vector
* @return a new vector, this - rhs
*/
public Vector2d sub(Vector2d rhs) {
return new Vector2d(x - rhs.x, y - rhs.y);
}

/**
* Negate a vector
* @return A new vector equal to -this
*/
public Vector2d neg() {
return new Vector2d(-x, -y);
}

/**
* Multiply a vector by a constant.
* @param d the constant by which the vector will be scaled.
* @return a new vector equal to d*this
*/
public Vector2d scale(float d) {
return new Vector2d(x * d, y * d);
}

/**
* Determine the magnitude of a vector.
* @return Return the magnitude of this
*/
public float mag() {
return (float) Math.sqrt(x*x + y*y);
}

/**
* Equality test for vectors.
* @param rhs The vector to compare to
* @return true if the vectors have the same components, false
othewise.
*/
public boolean equals(Vector2d rhs) {
return (x == rhs.x) && (y == rhs.y);
}
}




/**
* The Particle class represents a physical object moving through
* space. It has a position, a velocity, and a size. For simplicity,
* the shape is assumed to be a sphere.
*
*/
public class Particle {
// comma after Posistion
Vector2d Position, Velocity;
float Radius;

/**
* Constructor. Initialize the position, velocity and size
* of this object.
* @param pos The initial position vector of the object
* @param vel The initial velocity vector of the object.
* @param rad The radius of the object.
*/
public Particle(Vector2d pos, Vector2d vel, float rad) {
Position = pos;
Velocity = vel;
Radius = rad;
}

/**
* This performs a single step of the Euler method for integrating
* equations of motion. In short, it moves the particle a little bit
* based on its current velocity, and then updates the velocity a little
* bit based on the given acceleration vector.
* @param accel The acceleration vector acting on this particle
* @param timestep How long a time interval to apply.
*/
public void updateParticle(Vector2d accel, float timestep) {
Position = Position.add(Velocity.scale(timestep));
Velocity = Velocity.add(accel.scale(timestep));
}

/**
* Determines if two objects are in contact. Two spheres are in contact
if
* the separation between their centers is less (or equal to) their
combined
* radii.
* @param other The second object in the collision. The first is
"this".
* @return true if the two particles touch, false otherwise.
*/
public boolean collidesWith(Particle other) {
Vector2d displacement = Position.sub(other.Position);
float distance = displacement.mag();
return (distance <= (Radius));
}

// Here we have a set of accessor/mutator methods for getting/setting
// the member variables of the particle objects. These should be
// self explanitory.
//
// Note: We explicitly construct a *new* position and velocity vector
// when getting them to avoid giving a client program a direct reference
// to one of the Particle member variables.
public Vector2d position() { return new Vector2d(Position.X(),
Position.Y()); }
public Vector2d velocity() { return new Vector2d(Velocity.X(),
Velocity.Y()); }
public void position(Vector2d v) { Position = v; }
public void velocity(Vector2d v) { Velocity = v; }
public float radius() { return Radius; }
public void radius(float f) { Radius = f; }
}
 
Ad

Advertisements

J

Jeffrey Schwab

vtcompsci said:
i was trying to get some bugs out of my program but i cant get it to
compile... i get some horrable errors with PathDisplay.java

Could you please be more specific? The code compiled for me without
warnings, once I fixed the inadvertently line-wrapped comments and put
the three public classes into separate files. (NB: I have not actually
read the code, just compiled it.)
 
V

vtcompsci

i got it to compile and now it says that the 2 lines collided but i cant
get the blue line to stop wth th ball where there collide... the blue line
keeps going down to the bottom of the page
 
Ad

Advertisements

R

Roedy Green

i got it to compile and now it says that the 2 lines collided but i cant
get the blue line to stop wth th ball where there collide... the blue line
keeps going down to the bottom of the page

You are making a presumption that people understand what you program
is attempting to do.
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top