Could someone explain to me why I am getting these errors on my coding when it comes to the main method project5 class. thearray[count++] keeps giving me errors, and I am not entirely sure where I made my error. I've been stuck on it for awhile now. Some guidance would be nice.
Here is my main method:
public class Project5 {
private Shape [] thearray = new Shape[100];
public static void main (String [] args) {
Project5 tpo = new Project5();
tpo.run();
}
public void run () {
int count = 0;
thearray[count++] = new Circle(20, 20, 40);
thearray[count++] = new Triangle(70, 70, 20, 30);
thearray[count++] = new Rectangle(150, 150, 40, 40);
for (int i = 0; i < count; i ++ ) {
thearray[i].display();
}
int offset = 0;
double totalarea = 0.0;
while (thearray[offset] != null) {
totalarea = totalarea + thearray[offset].area();
offset++;
}
System.out.println("The total area for " + offset + " Shape objects is " + totalarea);
}
}
Here is my Circle class:
public class Circle {
private double radius;
public Circle() {
radius = 1.0;
}
public Circle(double newRadius) {
radius = 1.0;
setRadius(newRadius);
}
public void setRadius(double newRadius) {
if(newRadius > 0) {
radius = newRadius;
}
else {
System.out.println("Error: "
+ newRadius + " is a bad radius value.");
}
}
public double getRadius() {
return radius;
}
public double getArea() {
return radius * radius * Math.PI;
}
}
and here is my Shape class:
abstract class Shape{
int x = 1;
int y = 1;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public void display() {
}
public abstract double area();
}
I would post my triangle and rectangle class, but I figured this would be enough to at least have it explained where I am messing up.
I looked at your Circle class and the constructor currently only takes one argument. However, when you create a Circle you are specifying 3 arguments.
Circle should probably extend from Shape and the first two parameters are then the x and y position of the shape, correct? If this is the case, change your class as follows:
public class Circle extends Shape {
private double radius;
public Circle(int x, int y) {
super(x, y);
radius = 1.0;
}
public Circle(int x, int y, double newRadius) {
super(x, y);
setRadius(newRadius);
}
...etc
Related
So i need code that consist of 2 classes, method point that already formed and method rectangle that include constructor for creating rectangle itself, rectangle itself should be formed by this test
#Test
public void testRectangle2() {
Rectangle rect = new Rectangle(20, 30, 20, 20);
assertAll(
() -> assertEquals(10, rect.getTopLeft().getX()),
() -> assertEquals(20, rect.getTopLeft().getY()),
() -> assertEquals(30, rect.getBottomRight().getX()),
() -> assertEquals(40, rect.getBottomRight().getY()),
() -> assertEquals(20, rect.getWidth(), 20),
() -> assertEquals(20, rect.getHeight(), 20)
);
}
Class Point works fine, and i am ading it just for clarity
public class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
this(0, 0);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void moveTo(int newX, int newY) {
x = newX;
y = newY;
}
public void moveRel(int dx, int dy) {
x += dx;
y += dy;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
This is class for Rectangle itself, and it includes both constructor and aditional methods.
public class Rectangle {
public int width = 0;
public int height = 0;
public Point center;
public int xCenter;
public int yCenter;
public Point getTopLeft() {
Point point = new Point(center.getX(), center.getY());
point.moveRel(- width / 2, - height / 2);
return point;
}
public Point getBottomRight() {
Point point = new Point(center.getX(), center.getY());
point.moveRel(width / 2, height / 2);
return point;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Point getCenter() {
Point center = new Point(xCenter, yCenter);
return center;
}
public Rectangle(int xCenter, int yCenter, int width, int height) {
this.xCenter=xCenter;
this.yCenter=yCenter;
this.width=width;
this.height=height;
}
}
Problem is in the constructor it self, it should get values from the test and then form rectangle but it is not doing it.
There are several issues in this code.
The issue with constructor is that the center point is not created, then the test fails with NullPointerException in getTopLeft/getBottomRight whichever called first because these methods do not use getCenter() method but refer center field directly.
So, it should be enough just to use the mentioned getter in the mentioned methods and remove redundant field center.
class Rectangle {
public int width = 0;
public int height = 0;
public int xCenter;
public int yCenter;
public Point getTopLeft() {
Point point = getCenter();
point.moveRel(- width / 2, - height / 2);
return point;
}
public Point getBottomRight() {
Point point = getCenter();
point.moveRel(width / 2, height / 2);
return point;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Point getCenter() {
Point center = new Point(xCenter, yCenter);
return center;
}
public Rectangle(int xCenter, int yCenter, int width, int height) {
this.xCenter=xCenter;
this.yCenter=yCenter;
this.width=width;
this.height=height;
}
}
However, this design has certain flaws that Rectangle fields are public and may be changed from outside thus breaking encapsulation principle. Also, redundant points are created although they might be reused.
An improved version of the Rectangle class is below:
"immutable" fields
lazily initialized topLeft and rightBottom points
public class Rectangle {
private final int width;
private final int height;
private final int xCenter;
private final int yCenter;
private Point topLeft;
private Point bottomRight;
public Rectangle(int xCenter, int yCenter, int width, int height) {
this.xCenter = xCenter;
this.yCenter = yCenter;
this.width = width;
this.height = height;
}
public Point getTopLeft() {
if (null == topLeft) {
topLeft = getCenter();
topLeft.moveRel(- width / 2, - height / 2);
}
return topLeft;
}
public Point getBottomRight() {
if (null == bottomRight) {
bottomRight = getCenter();
bottomRight.moveRel(width / 2, height / 2);
}
return bottomRight;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Point getCenter() {
return new Point(xCenter, yCenter);
}
}
I have started with my first game but cannot figure out how the collision detection should work. The goal is that the player should not be able to go into the wall.
I have following classes Player(), Wall(), Levels() and Game()
Player class is loading the player and handling movement and collisions for the player.
Wall is creating walls, I have one Arraylist in this class which is creating an rectangle for each wall that is created.
Levels class is loading creating and loading all the levels.
Game class is handling the whole game loop and more.
I have tried to compare x and y positions with player and wall, right now I am trying to use the .intersect class which has not been succesfull yet.
Part of Player Class:
public void collision() {
Rectangle r3 = getOffsetBounds();
for (int i = 0; i < Wall.wallList.size(); i++) {
Rectangle w1 = Wall.wallList.get(i);
if (r3.intersects(w1)) {
}}}
public int moveUp(int velY) {
collision();
y -= velY;
return y;
}
public int moveDown(int velY) {
collision();
y += velY;
return y;
}
public int moveLeft(int velX) {
collision();
x -= velX;
return x;
}
public int moveRight(int velX) {
collision();
x += velX;
return x;
}
public Rectangle getOffsetBounds() {
return new Rectangle(x + velX, y + velY, width, height);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVelX() {
return velX;
}
public void setVelX(int velX) {
this.velX = velX;
}
public int getVelY() {
return velY;
}
public void setVelY(int velY) {
this.velY = velY;
}}
Part of Wall Class:
static ArrayList<Rectangle> wallList = new ArrayList<Rectangle>();
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setVisisble(Boolean visible) {
this.visible = visible;
}
public Rectangle getBounds() {
return new Rectangle(x,y,width,height);
}
public Rectangle setBounds(int x,int y,int width,int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return new Rectangle(x,y,width,height);
}}
Part of Levels class where the wall list is setting
if(level1[i][j]==1) {
w = new Wall(j*25, i*25, width, height);
w.paint(g);
Wall.wallList.add(w.setBounds(j*25+10, i*25+10, width, height));
}
Part of Game class where keybindings are
public void KeyBindings() {
keyManager.addKeyBinding(lvl, KeyEvent.VK_UP, "moveUp", (evt) -> {
lvl.player.moveUp(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_DOWN, "moveDown", (evt) -> {
lvl.player.moveDown(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_LEFT, "moveLeft", (evt) -> {
lvl.player.moveLeft(5);
});
keyManager.addKeyBinding(lvl, KeyEvent.VK_RIGHT, "moveRight", (evt) -> {
lvl.player.moveRight(5);
});
}
This is how I always handle any collisions
if (((x1<x2 && x1+w1>x2) || (x2<x1 && x2+w2>x1)) &&
((y1<y2 && y1+h1>y2) || (y2<y1 && y2+h2>y1)))
I'm having a hard time figuring out why when I create an Circle instance with no arguments and adding the values after with setters isn't working? When I delete the line Circle c3 = new Circle() my program works fine. I also can't call the getters to see if the setters worked.
public class MyCircle {
private double radius;
private double x;
private double y;
public MyCircle()
{
x = 0;
y = 0;
radius = 0;
}
public MyCircle(double X, double Y, double rad)
{
x = X;
y = Y;
radius = rad;
}
public void setX(double value)
{
x = value;
}
public void setY(double value)
{
y = value;
}
public void setRadius(double value)
{
radius = value;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
return (radius * radius) * Math.PI;
}
public boolean doesOverlap(MyCircle oC)
{
double distance = Math.sqrt((Math.pow(x - oC.x, 2) + Math.pow(y-oC.y, 2)));
if ((radius + oC.radius) > distance)
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args) {
Circle c3 = new Circle();
Circle c1 = new Circle(1.0, 2.0, 3.0);
Circle c4 = new Circle(1.0, 6.0, .5);
c3.setX(1.0);
c3.setY(2.0);
c3.setRadius(5.0);
System.out.println(c3.getArea());
System.out.println(c1.getRadius());
System.out.println(c1.toString());
System.out.println(c4.toString());
if (c1.equals(c4))
{
System.out.println("c1 equals c4");
}
else
{
System.out.println("c1 does not equal c4");
}
if (c1.doesOverlap(c4))
{
System.out.println("c1 Overlaps c4");
}
else
{
System.out.println("c1 Does Not Overlap c4");
}
}
}
Your class is called MyCircle not Circle. You are trying to create Circle objects.
Replace:
Circle c3 = new Circle();
With:
MyCircle c3 = new MyCircle();
your class name is MyCircle instead of Circle
change the name of the class for Circle
Or change where you instantiate for MyCircle
I'm creating a simple Java circle calculator but am having issues getting my KeyListeners to respond quickly. The x and y values in the Circle class are not stored immediately but rather when I delete the input. For example if I input 3 for x and 5 for y the Circle class is returning values of 0 until I delete the values, then it will return the proper values. My goal is to immediately display data related to this coordinates when the user enters values. I can't do this while the KeyListeners are lagging. Thank you.
**Edit: Just realized that the values will also be correct if I hit another key afterwards (like ctrl for example)
**2nd Edit: Added Circle code at bottom
**3rd Edit: Added Point code at bottom
Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CircleGUI extends JFrame
{
Circle c;
JFrame frame;
DecimalFormat df;
private JPanel panel;
private JLabel radiusLabel, areaLabel, coordinateLabel, containsPointLabel;
private JButton calculateButton;
private JTextField radiusTextField, xTextField, yTextField;
final int WINDOW_WIDTH = 500;
final int WINDOW_HEIGHT = 300;
public static void main(String[] args)
{
Circle c = new Circle();
CircleGUI test = new CircleGUI(c);
}
public CircleGUI(Circle c)
{
this.c = c;
setTitle("Circle Calculator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
df = new DecimalFormat("#.##");
setVisible(true);
}
private JPanel buildPanel()
{
radiusLabel = new JLabel("Enter radius:");
areaLabel = new JLabel();
radiusTextField = new JTextField(15);
calculateButton = new JButton("Calculate Area");
calculateButton.addActionListener(new CalculateAreaButtonListener());
coordinateLabel = new JLabel("Origin of the Circle:");
containsPointLabel = new JLabel("");
xTextField = new JTextField(4);
xTextField.addKeyListener(new xCoordinateTextFieldListener());
yTextField = new JTextField(4);
yTextField.addKeyListener(new yCoordinateTextFieldListener());
panel = new JPanel();
//panel.setLayout(new FlowLayout());
panel.add(radiusLabel);
panel.add(radiusTextField);
panel.add(calculateButton);
panel.add(areaLabel);
panel.add(coordinateLabel);
panel.add(xTextField);
panel.add(yTextField);
panel.add(containsPointLabel);
return panel;
}
private class CalculateAreaButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
areaLabel.setText(String.valueOf(df.format(calculateArea())));
}
public double calculateArea()
{
double radius = Double.parseDouble(radiusTextField.getText());
c.setRadius(radius);
return c.getArea();
}
}
private class xCoordinateTextFieldListener implements KeyListener
{
#Override
public void keyPressed(KeyEvent e)
{
double x;
if (!xTextField.getText().equals(null) && !xTextField.getText().equals(""))
{
x = Double.parseDouble(xTextField.getText());
c.setX(x);
}
}
#Override
public void keyReleased(KeyEvent e)
{
System.out.println("x: " + c.getX());
}
#Override
public void keyTyped(KeyEvent arg0)
{
}
}
private class yCoordinateTextFieldListener implements KeyListener
{
#Override
public void keyPressed(KeyEvent e)
{
double y;
if (!yTextField.getText().equals(null) && !yTextField.getText().equals(""))
{
y = Double.parseDouble(yTextField.getText());
c.setY(y);
}
;
}
#Override
public void keyReleased(KeyEvent e)
{
System.out.println("y: " + c.getY());
}
#Override
public void keyTyped(KeyEvent arg0)
{
}
}
}
Circle code:
public class Circle
{
//Instantiate and declare instance fields
Point origin = new Point();
double radius;
Circle(double radius)
{
this.radius = radius;
origin.setX(0);
origin.setY(0);
}
//Two arg-constructor
Circle(Point origin, double radius)
{
this.origin = origin;
this.radius = radius;
}
//Three-arg constructor
Circle(double xValue, double yValue, double radius)
{
origin.setX(xValue);
origin.setY(yValue);
this.radius = radius;
}
//Default constructor
Circle()
{
setX(0);
setY(0);
radius = 0;
}
//Copy constructor
Circle(Circle c)
{
setX(c.getX());
setY(c.getY());
radius = c.getRadius();
}
//Get origin of the circle
Point getOrigin()
{
return origin;
}
//Set origin of the circle
void setOrigin(Point point)
{
this.origin = point;
}
//Set x value
void setX(double x)
{
origin.setX(x);
}
//Get x value
double getX()
{
return origin.getX();
}
//Set y value
void setY(double y)
{
this.origin.setY(y);
}
//Get y value
double getY()
{
return origin.getY();
}
//Set radius field
void setRadius(double radius)
{
this.radius = radius;
}
//Get radius field
double getRadius()
{
return radius;
}
//Get area of the circle
double getArea()
{
//Use constant provided in the static method Math.PI
return Math.PI * (radius * radius);
}
//Translate instance fields to a human readable String
public String toString()
{
return "x: " + this.getX() + ", y: " + this.getY() + ", radius: " + this.radius;
}
//Compare whether two circles instance fields are equal
boolean equals(Circle c)
{
if (getX() == c.getX() && getY() == c.getY() && getRadius() == c.getRadius())
return true;
else
return false;
}
double getDistance(double xValue, double yValue)
{
double x = xValue - this.getX();
double y = yValue - this.getY();
return Math.sqrt((x * x) + (y * y));
}
double getDistance(Circle c)
{
//Initialize variables to x^2-x^1 and y^2-y^1
double x = c.getX() - this.getX();
double y = c.getY() - this.getY();
//Calculate distance to center of the circle
return Math.sqrt((x * x) + (y * y));
}
boolean containsPoint(double xValue, double yValue)
{
if (getDistance(xValue, yValue) <= radius)
return true;
else
return false;
}
//Test if two circle overlap
boolean doesOverlap(Circle c)
{
//Initialize sumOfRadii to the sum of both circles radius
double sumOfRadii = c.getRadius() + radius;
//If the distance to the center of the circle is less than or equal to the sum of the two circles radius then return true, otherwise return false.
if (getDistance(c) <= sumOfRadii)
return true;
else
return false;
}
}
Point Code:
public class Point
{
private double x;
private double y;
public Point(double xValue, double yValue)
{
x = xValue;
y = yValue;
}
public Point(Point p) {
this(p.x, p.y);
}
public Point() {
this(0, 0);
}
public void setX(double xValue)
{
this.x = xValue;
}
public double getX()
{
return x;
}
public void setY(double yValue)
{
this.y = yValue;
}
public double getY()
{
return y;
}
public boolean equals(Point otherPoint)
{
return (this.x == otherPoint.x) && (this.y == otherPoint.y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}
Keylistener is not the right choice for responding to changes in a text field. See How to Write a Document Listener for an alternate approach.
Firstly, I wouldn't use a KeyListener to monitor changes to a text field, a DocumentListener would provide more useful information to the changes of the underlying field, but an ActionListener would probably be more appropriate under these conditions.
Take a look at How to write an Action Listener and How to use text fields for more details
This is my class that everything is done in:
import java.awt.Color;
import java.awt.Graphics;
//This class will not compile until all
//abstract Locatable methods have been implemented
public class Block implements Locatable
{
//instance variables
private int xPos;
private int yPos;
private int width;
private int height;
private Color color;
//constructors
public Block () {}
public Block(int x,int y,int w,int h)
{
xPos = x;
yPos = y;
width = w;
height = h;
}
public Block(int x,int y,int w,int h, Color c)
{
xPos = x;
yPos = y;
width = w;
height = h;
color = c;
}
//set methods
public void setBlock(int x, int y, int w, int h)
{
xPos = x;
yPos = y;
width = w;
height = h;
}
public void setBlock(int x, int y, int w, int h, Color c)
{
xPos = x;
yPos = y;
width = w;
height = h;
color = c;
}
public void draw(Graphics window)
{
window.setColor(color);
window.fillRect(getX(), getY(), getWidth(), getHeight());
}
//get methods
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
//toString
public String toString()
{
String complete = getX() + " " + getY() + " " + getWidth() + " " + getHeight() + " java.awt.Color[r=" + color.getRed() + ", g=" + color.getGreen() + ", b=" + color.getBlue() + "]";
return complete;
}
}
and here is my interface class that has to be implemented:
public interface Locatable
{
public void setPos( int x, int y);
public void setX( int x );
public void setY( int y );
public int getX();
public int getY();
}
I haven't had formal instruction yet on interfaces/implementations and thus, am not sure what needs to be done to get the first class to run right
When you implementing an interface, you have to implement all the methods declared in that interface.
Interface is a contract that your implementing class must full fill.in your case your implementing class Block should implement the following methods to full fill the contract.
public void setPos( int x, int y);
public void setX( int x );
public void setY( int y );
public int getX();
public int getY();
public class Block implements Locatable {
public void setPos( int x, int y){
// your implementatioon code
}
public void setX( int x ) {
// your implementatioon code
}
public void setY( int y ){
// your implementatioon code
}
public int getX(){
// your implementatioon code
return (an int value);
}
public int getY(){
// your implementatioon code
return (an int value);
}
}
EDIT: for your NPE from the comments.
you never initialized your Color object.and trying to call a method on its refrence in your toString method.
private Color color;
initialize it like this
private Color color = new Color(any of the Color constructors);
check here for Color API