Hello!

I'm having a bit of confusion here regarding toStrings and Constructors. Namely, why would you ever need them?

I have a project for my course, and in it, I use a method that checks for a creature's "energyLevel" to see if that creature is still "alive". This method returns "true" or "false", and I think that I should probably use a toString() to convert something in one java file that gets called in a related java file. Here is the relevant code from the first file:

public boolean isAlive() {
       if (energyLevel > 0) {
           return true;
       }
       else {
           return false;
       } //end isAlive()
       // *after here I'm lost*

       public String toString() {
           return isAlive;
           }

That last "public String toString()" is not working at all. I imagine that I'm not doing the syntax correctly or, more likely, I'm making it up. I've done similar methods that return a variable, which I've successfully called from another java program, but I don't understand how to call more abstract things like "return true". Should I convert using toString()? If so, how? I've attached everything I have so far, just in case I didn't post enough code.

At the root, I'm not sure why or how I would you use toStrings to convert a boolean true/false to a string if I can just create a variable that gets changed inside your if/else clause.

On a completely similar note, how do I implement a "constructor", and under what conditions would they be useful?

I love the course I'm taking, and want to learn as much as I can, but these basic things are kind of weighing me down here. Any assistance would be greatly appreciated.

Recommended Answers

All 10 Replies

Member Avatar for iamthwee

Well if your parser or whatever, requires it to be a String then convert it to a String. If not, you're good to go.

I'm using Eclipse, and it's giving me a ton of errors. I'd really prefer more specific help if possible. Thanks!

Your comment in line 7 is revealing. It says that the ending bracket ends the function isAlive (). It does not. It ends the if-else statement. You need ANOTHER ending bracket after that to end the isAlive () function. Right now you have your toString () function INSIDE of your isAlive () function due to the lack of that ending bracket.

As for your toString () function, what exactly are you trying to return here? Normally, toString() will return a String representation of your class's data members. In your case, these are the sourceDNA and monsterDNA arrays and the energyLevel variable, so you'd have something similar to this maybe:

["A","B","C"],["D","E","F"],8.4

I forget the exact protocol for toString (). Is that what you're trying to do? If not, what are you trying to do with toString ()?

Thanks so much for helping, VernonDozier. You're dead on about the bracket issue.

Basically, I have been using methods in creature.java to test circumstances and return strings or arrays, which I can call in runCreature.java. However, my worksheet says that now my new method, isAlive(), has to return "true" or "false". That's obviously a concept, not a string, array, double, or integer, so how do I call that from runCreature.java?

Just re-read your first post. If you want it to return "true" or "false", I really doubt you want to name the method toString (). Or do you want to return a boolean variable that's either true or false (i.e. NOT the WORDS "true" or "false")?

isAlive is a function. You're using it as a variable. To return the String "true" or "false" based on the isAlive () function, do this:

Boolean b = isAlive ();
return b.toString ();

But again, if you do this, make sure you really want to name this function toString (), because normally that's not what toString () is.

I am assuming that you are trying to simply check if your "monster" is alive and if it is, say so in the console? If so, in your main method you simply need:

if( winston.getEnergy()) {
  System.out.println("This thing is alive");
}

As for your constructor question. A constructor is used to define your objects that you create. When you say "creature winston = new creature();", within the creature class, it will look for a method called creature(). Here is an example:

public class Monster {
        String [] sourceDNA = {"A", "E", "R"};
	String [] monsterDNA = new String[3];
	int energyLevel = 0;

   public static Monster(){
      energyLevel = 1;
   }
}


public class runMonster {
  public static void main(String[] args){
  Monster myMonster = new Monster();
  }
}

This myMonster object will start with an energyLevel of 1.

I hope this answers your question

Thanks so much for helping, VernonDozier. You're dead on about the bracket issue.

Basically, I have been using methods in creature.java to test circumstances and return strings or arrays, which I can call in runCreature.java. However, my worksheet says that now my new method, isAlive(), has to return "true" or "false". That's obviously a concept, not a string, array, double, or integer, so how do I call that from runCreature.java?

See my last post. Verify whether you want the words "true" or "false" (i.e. Strings) or a boolean function that returns true or false. Regardless, forget about writing a toString () function for this. The Boolean class already has one. You can even skip it altogether.

public String isAlive ()
{
  if (energyLevel > 0)
    return "true";

  return "false";
}

But again, double-check whether you want a return type of String or boolean. Lose the quotes above if it's boolean (and obviously change the function return type to "boolean". From my reading of your post, it's a boolean function, not a String.

VernonDozier: OH! I get it now! So it's not returning an abstract concept of "true" or "false" but rather a boolean variable which is SET to true or false which is then CALLED in the other program. Beautiful. To be honest, I really, really did not want to use toString(), but it was all I could think of that might accomplish the goal. This makes 100% more sense.

Foxh451: You nailed my second question! Thanks so much!

I appreciate the help that you guys offered today! You really saved my sanity! :-)

Vernon and previous posters are correct, keep in mind that the toString() method is usually used to display some description of an Object. You would write your own toString() method if you wanted to do just that . . for example, if you were writing an RPG, your toString might say

"I am a Super Mutant with 15 Health and I do 35 damage."

That's a stupid example, but toString is just a description of the Object. A class called "Shapes" might have a toString() method that was implemented for its subclasses to print out "I'm a circle" or "I'm a triangle".

constructors: When you use classes in future applications in Arrays/ArrayLists(for now, consider "String" is a class)
the Class, to be used must first be created, as a class is only a blueprint...when you create it, then it can be used (can you live in a blueprint peice of paper).
it helps fill the needed attributes on creation of the class which is very efficient, you are best asking your lecturer about "Classes as Objects" and "are classes only blueprints for the object?" (that should get any further needed information or just pm me if you wish)

toString: when you need to output the data from the class, the toString method is called on which gives you the chance to structure or manipulate the output given. (pm me if you need any more help)

any mistakes, post here AND pm me any corrections.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.