Re: overriding toString
On Apr 19, 1:58 pm, Alex.From.Ohio.J...@gmail.com wrote:
On Apr 19, 1:45 pm, conrad <con...@lawyer.com> wrote:
On Apr 19, 1:43 pm, conrad <con...@lawyer.com> wrote:
I have overriden toString in one of my classes
I craft a String object there much like this:
output = "Some text.\n"
output += "Some more text.\n";
output += "And some more text.\n";
return output;
In another class I create a PrintWriter
object and do the following for
an object of the class where I have
toString overriden:
printWriterObject.println(objectOfMyClass);
and upon looking at the text file that was
output all the new lines have been stripped
except the last that would correspond to
the use of println. Is this normal?
I should add that if I do not use a PrintWriter
object but instead send it to standard output,
then the output contains the newlines.
--
conrad
It looks like you spread logic of where to put new line in the string
to the different parts of your program.
Use KISS (keep it simple stupid) pattern.
Manage it all in one place (for example in toString() method) and
don't worry about it too much. Use print() method (not println) and
use \n in one place.
Point is that toString() or other methods shouldn't know or presume
where they are called. They shouldn't change their behavior or assume
what method call them.
Alex.http://www.myjavaserver.com/~alexfromohio/- Hide quoted text -
Just in case my post was not clear, I have
crafted up a small test case which demonstrates
my problem:
import java.io.*;
public class MyClass {
public static void main(String[] args) throws FileNotFoundException
{
MyClass foo = new MyClass();
System.out.println(foo);
File myFile = new File("c:\\java\\test.txt");
PrintWriter outputHandle = new PrintWriter(myFile);
outputHandle.println(foo);
outputHandle.close();
}
public String toString() {
String output = "Test 1\n";
output += "Test 2\n";
output += "Test 3\n";
return output;
}
}
sending the output to the standard output stream
produces the expected results.
Using PrintWriter to write it
to a file does not. Instead of
Test 1\nTest 2\nTest 3\n\n
written to a file, it is:
Test 1Test2 Test3\n
Why?
--
conrad