Hi all,
Im trying to create and write to a file to create a "list" type document that I can convert to .pdf and print out later on. Below is an example of what I'm doing. out is my file and list in a string array that holds the answers to the questions.

out.println("Is something red?                                                    " + list[0]);
out.println("Is something blue?                                                   " + list[1]);
out.println("Is my cat dumber than my dog?                                " + list[2]);
out.println("Will I have any hair left by the time I figure out Java?  " + list[3]);

I added the spaces into the strings to attempt to line up the answers for readability when I print out the file. All of this prints to my file, but instead of coming out lined up it comes out more like below...

Is something red? Yes
Is something blue?
No
Is my cat dumber than my dog? Yes
Will I have any hair left by the time I figure out Java?
No

Nothing lines up as expected except for the left justifications of the questions. And the exact placement of the list array items vary....sometimes the first 4 line up, sometimes none do...sometimes they're moved to the next line, etc...Any ideas would be greatly appreciated.

Thanks

Recommended Answers

All 3 Replies

Better use Formatter class.

seems like there is some trim() method calling going on somewhere under the hood. there are ways to insert a new line inside a string like using "\n". there might be similar for inserting space. I know there is for inserting a tab. consider that instead of just adding an empty string like this " " to your strings. do let us know if that works!

Using a formatted string was the solution. I placed all of the questions into an array so I could add them to the file with a for loop, and instead of using println() method I used format() and passed in the formatted string I made.

String format = "%1$-70s%2$-10s\n";

for(int i =0;i<questions.length;i++){
				out.format(format, questions[i],list[i]);
			}

The formatted string sets up the first parameter passed in to take up 70 spaces, and the second to take up 10, which lined everything up perfectly.

Thank you guys for your quick response and help. I really appreciate it.

Scott

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.