JavaSoftware

Word game solution in Java

Programming a word game is a common early challenge in most programming instruction. Here’s a word game along with a solution which reads in content and produces output. There are many ways to tackle this problem, so feel free to share your thoughts.

Word Game:
Write a program that plays a word game with the user. The program should ask the user to enter the following:

  • His or her name
  • His or her age
  • The name of a city
  • The name of a college
  • A profession
  • A type of animal
  • A pet’s name

After the user has entered these items, the program should display the following story, inserting the user’s input into the appropriate locations:

There once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. Then, NAME adopted a(n) ANIMAL  named PETNAME They both lived happily ever after!

Prompts And Output Labels: There are no labels here but the prompts should simply be (respectively) “Enter your name: “, “Enter your age: “, “Enter the name of a city: “, “Enter the name of a college: “, “Enter profession: “, “Enter a type of animal: “, “Enter a pet name: “. Note that each prompt ends with a “:” followed by one space and is displayed so that the response will appear on the same line as the prompt itself.

Here’s my solution using the Java programming language:

import java.util.Scanner;

public class WordGame {
    
    public static void main(String[] args) {
      Scanner kb = new Scanner(System.in);
        
      System.out.print("Enter your name: ");
      String name = kb.nextLine();
      System.out.print("Enter your age: ");
      String age = kb.nextLine();
      System.out.print("Enter the name of a city: ");
      String city = kb.nextLine();
      System.out.print("Enter the name of a college: ");
      String college = kb.nextLine();
      System.out.print("Enter profession: ");
      String profession = kb.nextLine();
      System.out.print("Enter a type of animal: ");
      String animal = kb.nextLine();
      System.out.print("Enter a pet name: ");
      String petName = kb.nextLine();
      
      System.out.println("There once was a person named "+name+" who lived in "+city+". "
              + "At the age of "+age+", "+name+" went to college at "+college+". "
              +name+" graduated and went to work as a "+profession+". Then, "+name+" adopted a(n) "
              + animal +" named "+petName+" They both lived happily ever after!");
      
    }
}

Leave a Reply