quasar-light quasar-light -4 years ago 66
Java Question

why is my code outputting the package.class@letternumbers in java?

as per usual I'd like to note I'M A BEGINNER, so sorry in advance if I don't use the correct terminology.

what i did:

I created a method that outputs a recipe in a separate class from the main. In the main class i created an object to call on the method from the other class.

From main:

Breakfast recipeName2 = new Breakfast();
recipeName2.frenchToast();
System.out.println(recipeName2);


From other Class:

public void frenchToast(){

System.out.println("\n");
StringBuilder sba = new StringBuilder("For French toast you will need:\n ");

sba.append("Eggs\n ");
sba.append("Bread\n ");
sba.append("Cinnamon\n ");
sba.append("Vanilla ");

System.out.println(sba.toString());

}

}


The problem:

Thought the recipe is outputted correctly, for some reason at the very end of it this is added as well: ingredients.Breakfast@1f96302

I'm not sure what it is or how to get rid of it. I've tried altering my code in different ways such as altering what i put in the system.out.ln() parameters, but it then messed up my code. I have a hunch this is happening because of the way something is being passed through something else, but i have tried to take alter the way i wrote my code to no avail.

I'd be very grateful if anyone could help me out. I'm continuing with my project since technically my code works, but i'm stumped by this and would really like to know why is it happening.

Thanks

Answer Source

Your error was is because of the line System.out.println(recipeName2); below I have shown can use either void or String in frenchToast() and frenchToast2() respectively:

class Main {
  public static void main(String[] args) {
    Breakfast recipes = new Breakfast();
    recipes.frenchToast();
    System.out.println(recipes.frenchToast2());
  }
}

class Breakfast {
  public void frenchToast(){
    StringBuilder sba = new StringBuilder("For French toast you will need:\n ");
    sba.append("Eggs\n ");
    sba.append("Bread\n ");
    sba.append("Cinnamon\n ");
    sba.append("Vanilla ");
    System.out.println(sba.toString());
  }

  public static String frenchToast2(){
    StringBuilder sba = new StringBuilder("For French toast you will need:\n ");
    sba.append("Eggs\n ");
    sba.append("Bread\n ");
    sba.append("Cinnamon\n ");
    sba.append("Vanilla ");
    return(sba.toString());
  }
}

Equivalent Output:

For French toast you will need:
 Eggs
 Bread
 Cinnamon
 Vanilla 
For French toast you will need:
 Eggs
 Bread
 Cinnamon
 Vanilla 

Try it here!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download