Public class square java

Public class square java

The Square class extends the Enumerate class and represents the different types of squares located on a map.

These types include:
1. empty space
2. robot
3. crate
4. incinerator
5. wall
6. starting position

Field Summary
static Square CRATE
static Square EMPTY
static Square INCINERATOR
static Square ROBOT
static Square STARTING_POSITION
static Square WALL
Constructor Summary
Square (java.lang.String name)
Constructor — calls the constructor of the Enumerate class that Square inherits.
Methods inherited from class Enumerate
get, get, getName, iterator, pos, readResolve, size, toArray, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

EMPTY


ROBOT


CRATE


INCINERATOR


WALL


STARTING_POSITION


Square

public Square(java.lang.String name)

Constructor — calls the constructor of the Enumerate class that Square inherits.

Parameters: name — the name of the square: empty, robot, crate, incinerator, wall, or starting position

Overview Class Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Источник

Java Square Class

Java Square Class [closed] Create a class called Square that takes a width parameter in the constructor. The Square class should have a draw () method that will draw the square on the screen. Create a class called TestSquare that will take width from the user, create an object of Square, and invoke the draw () method on the square object.

Читайте также:  Effective java 4th edition

«But the method you’re using to draw the square is the same as the rectangle! i should be set to 1 so that it would reiterate in the correct number of times And edit your getWidth() method into this: Using width*width would make the method return n^2 of the width.

Java Square Class

Here is what I am asked to do: 1. Create a class called Square that takes a width parameter in the constructor. The Square class should have a draw() method that will draw the square on the screen. Create a class called TestSquare that will take width from the user, create an object of Square, and invoke the draw() method on the square object.

Here is what I have, but the problem I am having is passing the draw() method to the test method. I know see that I need to move the for loops from the test to the class, so that i can call it in the test main method.

public class Square < /** the width of square*/ int width; /** construct the square*/ Square()< >/**construct a square */ Square(int newWidth) < width = newWidth; >/**show the square*/ void draw() < for (int i=0; iSystem.out.println(); > > > import java.util.Scanner; public class TestSquare < /** Main method */ public static void main(String[] args) < // Create a scanner input Scanner input = new Scanner(System.in); // prompt user to enter width System.out.println("Creating a Square . "); System.out.print("Please enter its width:"); int width = input.nextInt(); Square square = new Square(width); System.out.println("Here is the Square:"); square.draw(); >> 

Change your loop into this:

for (int i=0; i System.out.println(); > 

As said, remove semicolons after loops because this makes your loop end immediately without arguments. i should be set to 1 so that it would reiterate in the correct number of times

And edit your getWidth() method into this:

Using width*width would make the method return n^2 of the width. It’s supposed to be width not area.

Edit: I’m not sure if this is what you’re trying to do but try putting this inside Square class:

void draw() < for (int i=0; iSystem.out.println(); > > 

Remove the getWidth() method completely. Then replace your getWidth() invocation with this:

Either rename this method to «getArea» or return width only:

Do not put a semicolon at the end of the for loop declarations. That makes the for loop do nothing. Also, the outer for loop should start at 0 (not 1):

Java — Need a lot of help making a square class, I’m trying to make a square class using Dr. Java. I have taken most of the code from a rectangle class but it has left me with a mess. I’m currently a …

Create the square, rectangle, triangle of java in jframe

I have a problem with Java As I understood not come Draw Geometric figures in Java, the code and the Following you can help me?

public class Gioco < public static void main (String args []) < PaintRect(); >public static void PaintRect()

How can I create a JFrame the triangle, square and rectangle? correct my code thanks

Before I even start writing my answer I need to encourage you to read carefully to: How to create a valid Minimal, Complete and Verifiable Example and a Short, Self Contained, Correct Example.

    From your (now deleted) code, I see you haven’t gone through the Swing Tutorial on Custom Painting yet or you didn’t even pay attention to it, this line will cause you problems

static Graphics2D g = new Graphics2D() 
public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < public void run() < //Your constructor here >>); > 

After all the above has being said (and which you should read carefully) we can continue to the coding part:

In order to draw a rectangle we need to learn something about a rectangle:

  • A rectangle has a width and a height, both are different
  • The way to draw a rectangle in Swing is with drawRect(x, y, width, height) draw(Shape) of the Graphics2D method where Shape would be an instance of Rectangle2D

To draw a square we need to know that:

  • A square has a width and a height, both are equal size
  • The way to draw a square in Swing is with drawRect(x, y, width, height) draw(Shape) of the Graphics2D method where Shape would be an instance of Rectangle2D

You must be saying. «But the method you’re using to draw the square is the same as the rectangle!» , well. yep, we are, the difference lies in that we’re going to pass a width and height equal size for the square and different size for the rectangle.

To draw a triangle you need to know that:

  • A triangle has 3 sides, they can be same or different sizes
  • We have no method to drawTriangle in Swing, but we have drawPolygon(xPoints, yPoints, nPoints) draw(Shape) of the Graphics2D method, which will draw a Polygon of nPoints (3 in this case), taking the coords from each array element of xPoints for the X coords and yPoints for the Y coords and where Shape would be an instance of Polygon

Now, putting all that together we should have all that code in an overridden method of our JPanel called paintComponent() as shown in the tutorial (See point #1). It should look like this:

@Override protected void paintComponent(Graphics g) < super.paintComponent(g); //ALWAYS call this method first! g.drawRect(10, 10, 50, 50); //Draws square g.drawRect(10, 75, 100, 50); //Draws rectangle g.drawPolygon(new int[] , new int[] , 3); //Draws triangle > 

But we also need to override another method getPreferredSize() on our JPanel , (see: Should I avoid the use of setPreferred|Maximum|MinimumSize in Swing? the general consensus says yes), otherwise our JFrame will be smaller than what we want, so it should look like this:

@Override public Dimension getPreferredSize()

Don’t forget to call @Override in those methods!

With only those methods we have completed our program to draw the shapes, but I know that if I don’t post the whole code you’ll end up writing the above methods in a place that won’t work or cause you compilation errors, so the whole code (which in fact is a MCVE or SSCCE (see the very first paragraph in this answer to see what each means)) that produces the below output is:

import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class ShapesDrawing < private JFrame frame; private JPanel pane; public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < public void run() < new ShapesDrawing().createAndShowGui(); >>); > public void createAndShowGui() < frame = new JFrame(getClass().getSimpleName()); pane = new JPanel() < @Override protected void paintComponent(Graphics g) < super.paintComponent(g); //ALWAYS call this method first! g.drawRect(10, 10, 50, 50); //Draws square g.drawRect(10, 75, 100, 50); //Draws rectangle g.drawPolygon(new int[] , new int[] , 3); //Draws triangle g.dispose(); > @Override public Dimension getPreferredSize() < return new Dimension(300, 300); >>; frame.add(pane); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); > > 

I really hope you read every link I posted here, because it’s worth it

And if you need to fill the shapes then call fillRect and fillPolygon instead of drawRect and drawPolygon :

@Override protected void paintComponent(Graphics g) < super.paintComponent(g); //ALWAYS call this method first! g.drawRect(10, 10, 50, 50); //Draws square g.fillRect(150, 10, 50, 50); //Fills a square g.drawRect(10, 75, 100, 50); //Draws rectangle g.fillRect(150, 70, 100, 50); //Fills a square g.drawPolygon(new int[] , new int[] , 3); //Draws triangle g.fillPolygon(new int[] , new int[] , 3); //Fills triangle g.dispose(); > 

Edit

As per @MadProgrammer’s comment:

Could we avoid using draw/fillPolygon in favor of using the updated Shapes API . provides much more functionality and is generally easier to use 😛

Here’s the updated paintComponent method using the Shapes API:

@Override protected void paintComponent(Graphics g) < super.paintComponent(g); //ALWAYS call this method first! Graphics2D g2d = (Graphics2D) g; g2d.draw(new Rectangle2D.Double(10, 10, 50, 50)); g2d.fill(new Rectangle2D.Double(150, 10, 50, 50)); g2d.draw(new Rectangle2D.Double(10, 75, 100, 50)); g2d.fill(new Rectangle2D.Double(150, 75, 100, 50)); g2d.draw(new Polygon(new int[] , new int[] , 3)); g2d.fill(new Polygon(new int[] , new int[] , 3)); g2d.dispose(); g.dispose(); > 

Which produces the following output:

Java Math — W3Schools, The Java Math class has many methods that allows you to perform mathematical tasks on numbers. Math.max(x,y) The Math.max(x,y) method can be used to find …

Square and Rectangle Inheritance

This is a question in-regards to basic inheritance in Java with two classes.

We have two classes, with the first one being a Rectangle :

private double length; private double width; public Rectangle(double length, double width)

Next we have an extension class called Square , which extends Rectangle , so through super() we know that it uses the constructor of the Rectangle class.

private double side; public Square(double side) < super(side, side); this.side = side; >public void print()
Square b = new Square(6.0); Rectangle c = (Rectangle) b; c.print(); 

We create a object of the type Square , which would contain two side variables the double 6.0

Next, we cast b to Rectangle c , which is where my question comes in.

Why would c.print() print out I am a square of side 6.0 ?

This assumes Rectangle declares a print() method.

doesn’t do anything to the instance referenced by b . It only widens the reference variable b to its super type Rectangle .

Invoking print() will have polymorphic behavior and, at runtime, the implementation of Square will be used since c is referencing a Square object, which has set size to 6 .

Square b = new Square(6.0); . private double side; public Square(double side)

Note that this is the expected behavior in Java since all methods are virtual by default. In other languages like C++ and C#, your cast would have worked since print method in Rectangle isn’t declared as virtual .

This is polymorphic behavior. The actual type of the class determines the method that is called. Square ‘s version of print will be called since the actual type of the object is Square .

Polymorphy

In ( Java ) inheritance that is the intended behavior — polymorphy — it’s a way for you (the developer) to design an application around a concept (rectangles) and allow other related concepts (squares) to be used in places where the original concept (rectangle) is used but with their own (square) behavior.

Practicality

Imagine you’d have a list or array of rectangles and you’d fill it with objects received from returns of functions from outside your own package. Then you’d iterate over the list and ask each object to do things — it is normal to want those objects to behave as what they really are, not as what they’re filling in for.

If you ask a rectangle what its area is it will multiply length and width and return the result. If you don’t override that in the square class it will do the same thing but you could override it and it could calculate its area as Math.pow(this.side, 2) .

How about this inheritance chain:

Shape > Polygon > Quadrilateral > Parallelogram > Rectangle > Square 

You would definately need to implement different area calculation methods — wouldn’t you want each object to behave as its own underlying structure tells it to (instead of behaving like the type it’s been cast to)?

Because of inheritance, every Square is also a Rectangle . When you cast it to shove a Square in a Rectangle variable, it retains its Square ness. In this example, either a Square or a Rectangle can be put in your c . polymorphism means that the method on whatever class it really is will be used.

Java sqrt() method with Examples, The java.lang.Math.sqrt () returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the …

Источник

Оцените статью