This site requires JavaScript, please enable it in your browser!
Greenfoot back
Sinned007
Sinned007 wrote ...

2014/2/18

Making black keys (Book scenarios chapter 5)

Sinned007 Sinned007

2014/2/18

#
Hi there, Im new to Java and trying to understand the solution written in the book to solve the placing of the black key's on the piano. The book wants me to place 2 black, none, 3 black, non, 2 black, non, 1 black key. The array looks like this: private String blackKeys = { "W", "E", "", "T", "Y", "U", "", "O", "P", "", "]" }; I solved it like this: // make black keys if you find an blank in the array add 2 to the count and so skip a key public void makeBlackKeys() { int y = 0; while (y < blackKeys.length) { if (blackKeys.equals("")) { y++; } Key key = new Key(blackKeys, blackNotes + ".wav", "black-key.png", "black-key-down.png"); addObject(key, 87 + (y*63), 75); y = y + 1; } } And it does the trick. But the book comes up with this: for(int i = 0; i < whiteKeys.length-1; i++) { if( ! blackKeys.equals("") ) { Key key = new Key(blackKeys, blackNotes+".wav", "black-key.png", "black-key-down.png"); addObject(key, 85 + (i*63), 86); } } I can't seem to understand how 1. the "while" loop now is changed to a "for" loop? 2. It still makes keys when i does not equal "". 2. why deduct -1 and then i++. Could someone please talk me through the book solution for this? Dennis
danpost danpost

2014/2/18

#
(1) Often, 'while' and 'for' loops can be used interchangeably. The main difference is that the incrementing of the counter is done automatically with the 'for' loop (that is the 'i++' part). (2a) In your solution, you adjusted the counter to the next (non-empty string value of) blackKeys when one was found to be empty. In the book solution, the block of code adding a black key is only executed when the string is not empty (essentially skipping the empty strings). (2b) the structure of the 'for' statement usually has three parts: the initial value, the condition and the operation to execute between each time though the loop (usually incrementing a counter). In the book solution, the newly declared local (to the loop) field 'i' is set to zero. The condition to continue looping uses 'whiteKeys.length-1' (instead of 'blackKeys.length', which should be equivalent) as the limit. The operation to perform between loops is, in this case, indeed, an incrementing of the counter field 'i'.
Sinned007 Sinned007

2014/2/18

#
Thanks danpost, Ok so the count in the book continues (i++) for every time the loop is effective. The reason to use the "for" loop is to take care of this feature. And the "!" in if( ! blackKeys.equals("") ) takes care of the only make keys if the string is not empty. And the minus one !! Wow I didn't see the book uses the WHITEkeys string. It makes sense now. Thanks again :)
You need to login to post a reply.