Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Print out the state of an object.

  1. #1
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Print out the state of an object.

    Hi, I'm having trouble understanding what a question is asking. The first bit of the question i'm struggling with is "Write a toString() method for the Circle class that prints out the state of
    a Circle object." I don't know what it means but "the state", i've done some googling but still can't find it. Thanks for any help.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Print out the state of an object.

    The toString() method would exist in the Circle class and will return a String object of the important Circle state variables for the current object. What are the important state variables for each Circle object? I would guess x, y, and width/radius/diameter, depending on how you've defined the state, maybe color. So a toString method might return a String object:

    "The circle's state is: \n x = " + x + "\n y = " + y + . . . etc.

  3. #3
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Print out the state of an object.

    I keep getting an error if I name my method name is toString() but it's fine if I name it anything else. The error I'm getting is "toString() in Circle cannot override toString() in object." I've had a look through all my classes and can't find it anywhere so I don't know what to do. Thanks again!

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Print out the state of an object.

    The toString() method signature must be the same as that in the Object class. Check that, and if you still can't figure it out, post your Cicrle.toString() method.

  5. #5
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Print out the state of an object.

    I still can't find it. Here are the 3 classes, Circle.java, Canvas.java and ShapesTest.java:

    import java.awt.*;
    import java.awt.geom.*;
    import java.util.Vector;
     
    /**
     * A circle that can be manipulated and that draws itself on a canvas.
     * 
     * @author  Michael Kolling and David J. Barnes
     * @version 1.0  (15 July 2000)
     */
     
    public class Circle
    {
        private static int diameter;
        private static int xPosition;
        private static int yPosition;
        private static String color;
        private boolean isVisible;
     
        /**
         * Create a new circle at default position with default color.
         */
        public Circle()
        {
            diameter = 30;
            xPosition = 20;
            yPosition = 60;
            color = "blue";
            isVisible = false;
        }
     
    	public void toString()
    	{
    		System.out.println("The diameter of the circle is " + Circle.diameter);
    		System.out.println("The x position of the circle is " + Circle.xPosition);
    		System.out.println("The y position of the circle is " + Circle.yPosition);
    		System.out.println("The colour of the circle is " + Circle.color);
     
    	}
     
        /**
         * Make this circle visible. If it was already visible, do nothing.
         */
        public void makeVisible()
        {
            isVisible = true;
            draw();
        }
     
        /**
         * Make this circle invisible. If it was already invisible, do nothing.
         */
        public void makeInvisible()
        {
            erase();
            isVisible = false;
        }
     
        /**
         * Move the circle a few pixels to the right.
         */
        public void moveRight()
        {
            moveHorizontal(20);
        }
     
        /**
         * Move the circle a few pixels to the left.
         */
        public void moveLeft()
        {
            moveHorizontal(-20);
        }
     
        /**
         * Move the circle a few pixels up.
         */
        public void moveUp()
        {
            moveVertical(-20);
        }
     
        /**
         * Move the circle a few pixels down.
         */
        public void moveDown()
        {
            moveVertical(20);
        }
     
        /**
         * Move the circle horizontally by 'distance' pixels.
         */
        public void moveHorizontal(int distance)
        {
            erase();
            xPosition += distance;
            draw();
        }
     
        /**
         * Move the circle vertically by 'distance' pixels.
         */
        public void moveVertical(int distance)
        {
            erase();
            yPosition += distance;
            draw();
        }
     
        /**
         * Slowly move the circle horizontally by 'distance' pixels.
         */
        public void slowMoveHorizontal(int distance)
        {
            int delta;
     
            if(distance < 0) 
            {
                delta = -1;
                distance = -distance;
            }
            else 
            {
                delta = 1;
            }
     
            for(int i = 0; i < distance; i++)
            {
                xPosition += delta;
                draw();
            }
        }
     
        /**
         * Slowly move the circle vertically by 'distance' pixels.
         */
        public void slowMoveVertical(int distance)
        {
            int delta;
     
            if(distance < 0) 
            {
                delta = -1;
                distance = -distance;
            }
            else 
            {
                delta = 1;
            }
     
            for(int i = 0; i < distance; i++)
            {
                yPosition += delta;
                draw();
            }
        }
     
        /**
         * Change the size to the new size (in pixels). Size must be >= 0.
         */
        public void changeSize(int newDiameter)
        {
            erase();
            diameter = newDiameter;
            draw();
        }
     
        /**
         * Change the color. Valid colors are "red", "yellow", "blue", "green",
         * "magenta" and "black".
         */
        public void changeColor(String newColor)
        {
            color = newColor;
            draw();
        }
     
        /*
         * Draw the circle with current specifications on screen.
         */
        private void draw()
        {
            if(isVisible) {
                Canvas canvas = Canvas.getCanvas();
                canvas.draw(this, color, new Ellipse2D.Double(xPosition, yPosition, 
                                                              diameter, diameter));
                canvas.wait(10);
            }
        }
     
        /*
         * Erase the circle on screen.
         */
        private void erase()
        {
            if(isVisible) {
                Canvas canvas = Canvas.getCanvas();
                canvas.erase(this);
            }
        }
    }

    import javax.swing.*;
    import java.awt.*;
    import java.util.List;
    import java.util.*;
     
    /**
     * Canvas is a class to allow for simple graphical drawing on a canvas.
     * This is a modification of the general purpose Canvas, specially made for
     * the BlueJ "shapes" example. 
     *
     * @author: Bruce Quig
     * @author: Michael Kolling (mik)
     *
     * @version: 1.6 (shapes)
     */
    public class Canvas
    {
        // Note: The implementation of this class (specifically the handling of
        // shape identity and colors) is slightly more complex than necessary. This
        // is done on purpose to keep the interface and instance fields of the
        // shape objects in this project clean and simple for educational purposes.
     
        private static Canvas canvasSingleton;
     
        /**
         * Factory method to get the canvas singleton object.
         */
        public static Canvas getCanvas()
        {
            if(canvasSingleton == null) {
                canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, 
                                             Color.white);
            }
            canvasSingleton.setVisible(true);
            return canvasSingleton;
        }
     
        //  ----- instance part -----
     
        private JFrame frame;
        private CanvasPane canvas;
        private Graphics2D graphic;
        private Color backgroundColour;
        private Image canvasImage;
        private List objects;
        private HashMap shapes;
     
        /**
         * Create a Canvas.
         * @param title  title to appear in Canvas Frame
         * @param width  the desired width for the canvas
         * @param height  the desired height for the canvas
         * @param bgClour  the desired background colour of the canvas
         */
        private Canvas(String title, int width, int height, Color bgColour)
        {
            frame = new JFrame();
            canvas = new CanvasPane();
            frame.setContentPane(canvas);
            frame.setTitle(title);
            canvas.setPreferredSize(new Dimension(width, height));
            backgroundColour = bgColour;
            frame.pack();
            objects = new ArrayList();
            shapes = new HashMap();
        }
     
        /**
         * Set the canvas visibility and brings canvas to the front of screen
         * when made visible. This method can also be used to bring an already
         * visible canvas to the front of other windows.
         * @param visible  boolean value representing the desired visibility of
         * the canvas (true or false) 
         */
        public void setVisible(boolean visible)
        {
            if(graphic == null) {
                // first time: instantiate the offscreen image and fill it with
                // the background colour
                Dimension size = canvas.getSize();
                canvasImage = canvas.createImage(size.width, size.height);
                graphic = (Graphics2D)canvasImage.getGraphics();
                graphic.setColor(backgroundColour);
                graphic.fillRect(0, 0, size.width, size.height);
                graphic.setColor(Color.black);
            }
            frame.setVisible(visible);
        }
     
        /**
         * Draw a given shape onto the canvas.
         * @param  referenceObject  an object to define identity for this shape
         * @param  color            the color of the shape
         * @param  shape            the shape object to be drawn on the canvas
         */
         // Note: this is a slightly backwards way of maintaining the shape
         // objects. It is carefully designed to keep the visible shape interfaces
         // in this project clean and simple for educational purposes.
        public void draw(Object referenceObject, String color, Shape shape)
        {
            objects.remove(referenceObject);   // just in case it was already there
            objects.add(referenceObject);      // add at the end
            shapes.put(referenceObject, new ShapeDescription(shape, color));
            redraw();
        }
     
        /**
         * Erase a given shape's from the screen.
         * @param  referenceObject  the shape object to be erased 
         */
        public void erase(Object referenceObject)
        {
            objects.remove(referenceObject);   // just in case it was already there
            shapes.remove(referenceObject);
            redraw();
        }
     
        /**
         * Set the foreground colour of the Canvas.
         * @param  newColour   the new colour for the foreground of the Canvas 
         */
        public void setForegroundColor(String colorString)
        {
            if(colorString.equals("red"))
                graphic.setColor(Color.red);
            else if(colorString.equals("black"))
                graphic.setColor(Color.black);
            else if(colorString.equals("blue"))
                graphic.setColor(Color.blue);
            else if(colorString.equals("yellow"))
                graphic.setColor(Color.yellow);
            else if(colorString.equals("green"))
                graphic.setColor(Color.green);
            else if(colorString.equals("magenta"))
                graphic.setColor(Color.magenta);
            else if(colorString.equals("white"))
                graphic.setColor(Color.white);
            else
                graphic.setColor(Color.black);
        }
     
        /**
         * Wait for a specified number of milliseconds before finishing.
         * This provides an easy way to specify a small delay which can be
         * used when producing animations.
         * @param  milliseconds  the number 
         */
        public void wait(int milliseconds)
        {
            try
            {
                Thread.sleep(milliseconds);
            } 
            catch (Exception e)
            {
                // ignoring exception at the moment
            }
        }
     
        /**
         * Redraw ell shapes currently on the Canvas.
         */
        private void redraw()
        {
            erase();
            for(Iterator i=objects.iterator(); i.hasNext(); ) {
                ((ShapeDescription)shapes.get(i.next())).draw(graphic);
            }
            canvas.repaint();
        }
     
        /**
         * Erase the whole canvas. (Does not repaint.)
         */
        private void erase()
        {
            Color original = graphic.getColor();
            graphic.setColor(backgroundColour);
            Dimension size = canvas.getSize();
            graphic.fill(new Rectangle(0, 0, size.width, size.height));
            graphic.setColor(original);
        }
     
     
        /************************************************************************
         * Inner class CanvasPane - the actual canvas component contained in the
         * Canvas frame. This is essentially a JPanel with added capability to
         * refresh the image drawn on it.
         */
        private class CanvasPane extends JPanel
        {
            public void paint(Graphics g)
            {
                g.drawImage(canvasImage, 0, 0, null);
            }
        }
     
        /************************************************************************
         * Inner class CanvasPane - the actual canvas component contained in the
         * Canvas frame. This is essentially a JPanel with added capability to
         * refresh the image drawn on it.
         */
        private class ShapeDescription
        {
            private Shape shape;
            private String colorString;
     
            public ShapeDescription(Shape shape, String color)
            {
                this.shape = shape;
                colorString = color;
            }
     
            public void draw(Graphics2D graphic)
            {
                setForegroundColor(colorString);
                graphic.fill(shape);
            }
        }
     
    }

    public class ShapesTest
    {
       public static void main(String[] args)
       {
            Canvas c = Canvas.getCanvas();
            Circle c1 = new Circle();
            Circle c2 = new Circle();
    		c1.tosString();
            c1.makeVisible();
            c2.makeVisible();
     
     
       }
    }

    Thanks!

  6. #6
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Print out the state of an object.

    Quote Originally Posted by JaAnTr View Post
    public class Circle
    {
        private static int diameter;
        private static int xPosition;
        private static int yPosition;
        private static String color;
        private boolean isVisible;
    One issue you should consider immediately: class (static) variables for diameter and other values is really not a good thing (unless you have a very good reason for this, that you should explain). Class variables are shared between all instances of Circle. You cannot have a Circle object with diameter 10 and, at the same time, another Circle object with diameter 20!
    Use instance (non static) variables.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  7. The Following User Says Thank You to andbin For This Useful Post:

    ChristopherLowe (December 7th, 2013)

  8. #7
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Print out the state of an object.

    Am I supposed to be changing
    private static int diameter;
    to
    private instance int diamater

    Because if I do that then I get an error saying <identifier> expected.

    Thanks!

  9. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Print out the state of an object.

    What can't you find? If you mean you can't find the API page for the Object class, here it is. As I hope you can see, the signatures are different. Fix the toString() method signature in your Circle class. If you can't see that the signatures are different, say so, and we'll show you how to read an API page.

    Where have you learned that this line,

    private instance int diamater

    (misspellings/typos included) makes any sense in Java?

  10. #9
    Member
    Join Date
    Dec 2013
    Posts
    31
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Print out the state of an object.

    I didn't think it did but I was just trying what andbin suggested but I clearly misunderstood. Originally I hadn't set them to static so they were just:
        private int diameter;
        private int xPosition;
        private int yPosition;
        private String color;
        private boolean isVisible;

    But when I ran this I got an error on the Circle.diameter, Circle.xPosition etc saying that a non-static variable cannot be referenced from a static context. So I set them to static because I couldn't find any other way to do it.

  11. #10
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Print out the state of an object.

    Quote Originally Posted by JaAnTr View Post
    But when I ran this I got an error on the Circle.diameter, Circle.xPosition etc saying that a non-static variable cannot be referenced from a static context. So I set them to static because I couldn't find any other way to do it.
    Your code has several flaws, technical but also conceptual.

    First, in an instance method, instance variables can be accessed with this.name or simply name (because the this can be implicit).

    Second, the method form:

    public void toString()

    is invalid and does not compile.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  12. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Print out the state of an object.

    And it's interesting that you'd post some code written by randoms some 13 years ago without even disguising the fact. I'm getting the impression that you have little to no idea what you're doing. When you have a minimal understanding of how to do something, do you imagine it's easier to start from scratch and learn how to do it correctly as you go, OR start with someone else's broken attempt and fix it to do what you need?

    I won't help you fix someone else's code copied indiscriminately from the Internet to suit your purpose.

Similar Threads

  1. Beginner : Using a loop to print object array
    By trancecommunity in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 5th, 2013, 06:31 PM
  2. Replies: 1
    Last Post: December 3rd, 2012, 02:35 PM
  3. State UML Diagram
    By calebite207 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 18th, 2012, 12:30 PM
  4. Reading from ResultSet to Object and from object Object Array
    By anmaston in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 7th, 2011, 06:11 AM
  5. Print out object that is in a tree
    By dubois.ford in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 26th, 2010, 02:25 AM