Saturday, 17 December 2011

Java: String Formatting

First off: To Damian in the comments: The game could kick the player when its discovered they're broke, but that's not up to the player class! It's up to either the Table or the ConsoleClient!

Okay! Short post today, just covering string formatting. We saw in some code there was a string returned that looked roughly like:

"This is the message, %s, %f"


...within a method that took 2 more parameters. When printed out this way, the first parameter, the string, is the format of the message to be printed out. A percentage sign followed by a letter denotes where you'll want to put data in afterwards.



Think of the string as the template, and any %_ as data to be put into said template. An 's' denotes a string, 'f' denotes a float (real number in standard notation) and 'c' is for single characters. There are more, but this is just the general idea. Once you have your template in place...

"This is a template, it was written by %s who spend %f minutes on it"


...you can place a string and a float in there, in that order, probably in the form of some variable, like so:

String USER_NAME = "heddin";
float TIME_SPENT = 1.0;


...and then you print by having the string followed by 2 more parameters, like so:

String myString = String.format(`This is a template, it was written by %s who spent %f minutes on it`, USER_NAME, TIME_SPENT);


It`s really not hard, play with it if you`re having troubles getting it! Or just ask a question in the comments! Comments also welcome, and see you tomorrow for another refresher dealy! See ya!

5 comments:

  1. I had to read it a couple of times before it clicked... it's a lot harder without the pictures for some reason.

    ReplyDelete
  2. Hsh, okay, I'll make sure to include pictures tomorrow, then!

    ReplyDelete