Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Getting an object to print to string (instead of hashcode.)

This is a homework assignment. The object ( a triangle, which extends the abstract Geometric Object class) is created with methods color, filled, area and perimeter. The triangle is created but all I get is hashcode and the words in my "toString". I know there are mistakes in the expression of the "toString" but I won't be able to fix them until I can see the actual Triangle. My professor says I am close but I just don't know how to fix the error that causes only the hashcode to be printed. I would be grateful for hints and help. I love being part of this community and look forward to the end of the school year so I can resume the Android Development track. Finals.

(this is what prints - run: Enter color and isFilled (true or false): blue true Enter three points for a triangle: 1 2 3 4 5 6 Triangle@6796a753The null triangle isfalse. It has area of 0.0 and perimeter of 0.0.BUILD SUCCESSFUL (total time: 9 seconds))

import java.util.Scanner;
class GeometricObject {   
String color;
boolean filled;
double area;
double perimeter;

  /** Construct a geometric object with the specified color 
    *  and filled value */
  GeometricObject() { }
  /** Return color */
  public String getColor() {
    return color;
  }

  /** Set a new color */
  public void setColor(String color) {
    this.color = color;
  }

  /** Return filled. Since filled is boolean, 
     its get method is named isFilled */
  public boolean isFilled() {

    return filled;
  }

  /** Set a new filled */
  public void setFilled(boolean filled) {
         if (filled == true){
          System.out.println(" is filled");
      }else{
          System.out.println(" is not filled");
      }
    this.filled = filled;

  }

  public static void main(String[]args){

      System.out.print("Enter color and isFilled (true or false): " );

      Scanner input = new Scanner(System.in);
      String color = input.next();
      boolean filled = input.nextBoolean();

     System.out.print("Enter three points for a triangle: ");

      double x1 = input.nextDouble();
      double y1 = input.nextDouble();
      double x2 = input.nextDouble();
      double y2 = input.nextDouble();
      double x3 = input.nextDouble();
      double y3 = input.nextDouble();

      double d1 = (((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1)));
      double d2 = (((x2 - x3)*(x2 - x3)) + ((y2 - y3)*(y2 - y3)));
      double d3 = (((x3 - x1)*(x3 - x1)) + ((y3 - y1)*(y3 - y1)));

      double side1 = (Math.sqrt(d1));
      double side2 = (Math.sqrt(d2));
      double side3 = (Math.sqrt(d3));


    GeometricObject Triangle = new GeometricObject();
    Triangle myTriangle1 = new Triangle(); 


    //Triangle myTriangle1 = new Triangle(side1, side2, side3);

    System.out.print(myTriangle1.toString() );

    //System.out.printf("It has area %,.2f and perimeter %,.2f.", area, perimeter);


}
 public class Triangle extends GeometricObject {
    public double side1;
    public double side2;
    public double side3;
    double area;
    double perimeter;

    public Triangle() {
    }

    public Triangle(double side1, double side2, double side3){
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;

    } 

   //Triangle myTriangle1 = new Triangle(side1, side2, side3);

    public Triangle(double side1, double side2, double side3, 
            String color, boolean filled){
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
        setColor(color);
        setFilled(filled);

    }
    public void setArea(double side1, double side2, double side3){
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;

    }    

   public double getArea(){
       area = (side1 + side2 + side3)/2;
       return area;
}
    public double getPerimeter(){
        perimeter = side1 + side2 + side3;
        return perimeter;
    }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }

  public boolean isFilled() {


     return filled;

  }
  public void setFilled(boolean filled) {
    this.filled = filled;
  }


   @Override
        public String toString() {
            return super.toString() + "The " + this.getColor() + " triangle is" + 
                    this.isFilled() +". It has area of " + this.getArea() + " and perimeter of " + 
                            this.getPerimeter() + ".";
   }   

  /*public void printObject() {
    System.out.print("The "  + Triangle.getColor() + "triangle is" + Triangle.isFilled() + " .\n");
    System.out.printf("The area is %,.2f%, and the perimeter is %,.2f%", getArea(), getPerimeter());
*/
  }

7 Answers

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey Nancy, I'll give this a shot. What happens if you remove your super.toString before your return statement. Say something like.

@Override

public String toString() {
return "The " + this.getColor() + " triangle is" + 
                    this.isFilled() +". It has area of " + this.getArea() + " and perimeter of " + 
                            this.getPerimeter() + ".";
}

You may also want to use a String.format to clean the code up a bit, but that is just my opinion, Both of these methods work.

@Override

  public String toString() {
  return String.format("The %s triangle is %b. It has area of %1.1f and a perimeter of %1.1f.", 
                             this.getColor(), this.isFilled(),this.getArea(),this.getPerimeter());
}

What the trouble was is you were returning the super's toString() object, which was automatically made to print out the hash code reference. When you Override a method you are overriding the child class's toString Method, and leaving the Super's alone, so Java got confused as you were contradicting yourself.

With that being said, you did a good job and pretty much had it yourself, Good job keep up the good work!

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

A huge improvement. Your code made the print out coherent and got rid of the hash. I figured out that I needed to pass information the constructor. But it is only accepting the sides, not the color and fill status. So this is where I am, print statement wise.....

Enter color and isFilled (true or false): red true Enter three points for a triangle: 1 2 3 4 5 6 The null triangle is false It has area of 5.7 and a perimeter of 11.3.BUILD SUCCESSFUL (total time: 7 seconds)

I'll keep working on it and I may send it to the prof for help. If you have any ideas about passing color and fill, send them my way.

Have a good rest of the week.

Nancy M.

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey Nancy,

Sorry I wasn't sure if you wanted me to go that more into detail in this.

To properly set the color of your triangle after you declare myTriangle1.

use your setColor method.

myTriangle1.setColor(color);

This will set whatever color you had passed in once it was asked.

The boolean String representation is a bit more complicated, but doable. First declare a method that returns a string, and we'll change the string based on the boolean status of isFilled();

Mine looks like

public String filled() {
      if (this.isFilled()) {
          return "Filled";
      }
      else {
          return "not Filled";

      }

  }

and I just added it underneath your setFilled() method.

Now we just need to change the boolean value in the overridden to String method to return the result of this method instead of returning the boolean of true or false.

public String toString() {
  return String.format("The %s triangle is %s. It has area of %1.1f and a perimeter of %1.1f.", this.getColor(), this.filled(), this.getArea(), this.getPerimeter());

This should fix both of these problems.

Shoot me back if these cause you trouble.

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Ha. This is great...the only trouble now is me and my tiny little brain.

I have been studying Java (independent of Android) for about a year. A couple of concepts have taken a long time for me for grasp (arrays and objects.) Objects are especially daunting. I think I need more precise direction until I get used to the expressions and logic...I have feared that I will remain forever an input/output moron.

I'll keep at it. I've been enjoying Treehouse too but right now the finals in the on the ground courses I am taking have to come first in the triage....looking forward to summer. This is a great resource for me.

Nancy

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey Nancy don't beat yourself up. Java is very verbose which can be confusing. Your code was good you just had a small error in returning the super's to String.

Glad you enjoy treehouse, were always here to help when. asked.

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Thanks again for your support and your kind props. I think the fact that I write clean code is partly due to my professor's influence so I will share that with him.

I fixed those things and ran it in the auto grader and earned an 80%. It did not match one boolean, which is really weird (it's not like Math, it's one or the other...right? Hmmm). Anyway, I don't have the autograder data so I have no way to figure it out, I also shared that with the prof.

Having a couple of good Community College programs locally AND access to Treehouse has been hugely helpful to me....and I do look forward to the end of the term, so I can finish the Android track and tackle Java and Python. I love it here and wish I had more time now. Thanks.

Nancy Melucci

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

That is weird even if the boolean was passed a value of null it would still print is not filled. Let me know what the professor says if anything at all.

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Eh it was me. The error just didn't show up on 3 of the tests. I fixed my code. Live and learn as they say.

I don't want to exploit your kindness, let me see if I can ask a question about a difficult program we have assigned as part of a lab contest.

What type of methods should I design for a program that reads a line of letters (string codes) and turns them into information about a football game, it's final score and the team's record for the season?

So this: String data = "NS NV Steelers stp TD TD EP TD ep ep GO NV Seahawks TP td td TD GO";

becomes THIS:

run: The Chargers defeated Steelers 19 to 0 Chargers are now 1-0 The Seahawks defeated Chargers 12 to 6 Chargers are now 1-1

just point me it the right direction, and I will struggle to get there. I am trying various things but I don't feel very confident about any of them.

This will be my last question for the short term, I promise.

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey Nancy,

This one will be a bit tougher, but looks to be certainly doable

The first thing that came to mind is that you should come up with a method that will split that string up and eliminate the spaces between the separate words, you'll probably also want to save this to an array, so that you get an array of each word, instead of a clump of them broken up. ( I'd look at String.split() )

Once you have the initial string saved into an array that contains each word individually, you can start to make a method that has a loop that goes through each item in the array (IE each word in the String).

Now I have a question, in this example does he give he a key with what each word symbol or word means, or do you have to figure it out.

In any case, in your method that loops through each word of the string you'll need to have it check to see if that word holes any significance, and have it update the variables that you used to keep track of the results, rather it be points or not.

Thanks I know this eemed like a confusing answer, I'll clarify

Must have's:

Method that turns your initial string into an array of string that splits the string at each blank space.

Another method that loops through each string inside your newly created string array and checks to see if it equals a value that is contained in the key (if one is provided if not the code will have to be cracked)

Variables that track things like score and wins and losses, and when a keyphrase like the one in the frist String is met it adjusts the value, rather by adding more points, or another loss.

Thanks, don't hesitate to shoot back if you have more questions.

Nancy Melucci
PLUS
Nancy Melucci
Courses Plus Student 35,157 Points

Ah, it's a lot tougher. I'll be working on it for the next few days (unless one of my teammates writes it...it's a team coding contest.)

There is a key - it's the standard points for fooball plays (6 for a touchdown etc.) and a few other things relevant to the final print out.

Thanks for the hints. I am very grateful for any help I get here. See you here again soon.

Nancy M.