104k views
4 votes
In Java only please:

4.15 LAB: Mad Lib - loops
Mad Libs are activities that have a person provide various words, which are then used to complete a short story in unexpected (and hopefully funny) ways.

Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the example below. The program repeats until the input string is quit and disregards the integer input that follows.

Ex: If the input is:

apples 5
shoes 2
quit 0
the output is:

Eating 5 apples a day keeps you happy and healthy.
Eating 2 shoes a day keeps you happy and healthy

User Bekim
by
7.6k points

1 Answer

4 votes

Answer:

Step-by-step explanation:

import java.util.Scanner;

public class MadLibs {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String word;

int number;

do {

System.out.print("Enter a word: ");

word = input.next();

if (word.equals("quit")) {

break;

}

System.out.print("Enter a number: ");

number = input.nextInt();

System.out.println("Eating " + number + " " + word + " a day keeps you happy and healthy.");

} while (true);

System.out.println("Goodbye!");

}

}

In this program, we use a do-while loop to repeatedly ask the user for a word and a number. The loop continues until the user enters the word "quit". Inside the loop, we read the input values using Scanner and then output the sentence using the input values.

Make sure to save the program with the filename "MadLibs.java" and compile and run it using a Java compiler or IDE.

User Emperatriz
by
7.9k points