Reputation: 11
I am doing an online course and I got a program to solve. I have written the code and it is displaying the correct output, but I need to print the lines in a single line. Can anyone help me with that.
How i can display a multi-line text in a single line. The code written by me is as follows:
var num = 99;
while (num >= 1) {
if (num > 2) {
console.log("" + num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... " + (num - 1) + " bottles of juice on the wall!");
} else if (num === 2) {
console.log("" + num + " bottles of juice on the wall! " + num + " bottles of juice! Take one down, pass it around... " + (num - 1) + " bottle of juice on the wall!");
} else {
console.log("" + num + " bottle of juice on the wall! " + num + " bottle of juice! Take one down, pass it around... " + (num - 1) + " bottle of juice on the wall!");
}
num = num - 1;
}
Upvotes: 1
Views: 1945
Reputation: 43880
push()
each string into an array then use join()
. In the following demo I used ES6 template literals for the string. while()
is sufficient but for
is better in IMO.
Added a condition when bottles <= 2
to use .replace()
to output that particular string grammatically correct (i.e. 1 bottle
).
const wall = [];
for (let bottles = 99; bottles >= 1; bottles--) {
let str = ` ${bottles} bottles of beer on the wall! ${bottles} bottles of beer! Take one down, pass it around... ${bottles - 1} bottles of beer on the wall!`;
if (bottles <= 2) {
str = str.replace(/1 bottles/g, `1 bottle`);
}
wall.push(str);
}
console.log(wall.join(''));
Upvotes: 1
Reputation: 3032
As @Nisarg Shah mentioned in the comments, you can have a global variable declared outside of the loop that the code inside the loop keeps adding to.
Once the loop is over, the code can output the string stored in the variable as a single line using console.log
.
var output = "";
var num = 99;
while (num >= 1) {
var pluralSuffix = num != 1 ? "s" : "";
var nextNum = num - 1;
var nextPluralSuffix = nextNum != 1 ? "s" : "";
output += num + " bottle" + pluralSuffix + " of juice on the wall! " + num + " bottle" + pluralSuffix + " of juice! Take one down, pass it around... " + nextNum + " bottle" + nextPluralSuffix + " of juice on the wall! ";
num = nextNum;
}
console.log(output);
Upvotes: 1