In the String Variables tutorial we output the lines of a verse of ten green bottles, having output various sections of the verse at a time. Sometimes it's necessary to join elements together before outputting them.
Consider the example from the task:
String wallPhrase = " green bottles hanging on the wall";
System.out.print("10");
System.out.print(wallPhrase);
System.out.print(", ");
System.out.print("10");
System.out.print(wallPhrase);
System.out.print(", and if one green bottle should accidentally fall, there'd be ");
System.out.print("9");
System.out.print(wallPhrase)
There are a lot of print statements here.
+
operator as follows:String wallPhrase = " green bottles hanging on the wall";
System.out.print("10" + wallPhrase + ", ");
System.out.print("10" + wallPhrase + ", ");
System.out.print("and if one green bottle should accidentally fall, there'd be ");
System.out.print("9" + wallPhrase);
This results in more succinct, but still readable code.Taking your copy of the 'if you're happy and you know it task', modify the code so that you print an entire line of the song at a time
At the moment the output from this method all appears on one line, however it would be useful to separate the lines of the song. Whilst we could use System.out
's println
method in this case, few programmes in reality output text this way, so we need to learn how to add new lines within our text, and it's fairly simple - we just use the text \n
inside the string
String wallPhrase = " green bottles hanging on the wall";
System.out.print("10" + wallPhrase + ",\n");
System.out.print("10" + wallPhrase + ",\n");
System.out.print(" and if one green bottle should accidentally fall, there'd be ");
System.out.print("9" + wallPhrase);
println
methodAmend the 'if you're happy and you know it' code so that it uses the print
method instead of println
, ensuring that line breaks are included instead.
Modify the ten green bottles code, so that the word accidentally appears in double quotation marks.