Thursday, September 19, 2013

Case Study: Using Strings (Haiku)

Obviously I am out again today, so I am having to change it up a little bit.  Here's another program that I want you to play with.  This one uses strings and an interesting approach to formatting.  I commented some of the code to help you figure it out.

We're building a program that will generate Haiku poetry based on user input.  A haiku is a poem in 3 lines -- a line of 5 syllables, a line of 7 syllables, and a line of 5 syllables again.

Some examples of Haiku:
Falling to the ground,
I watch a leaf settle down
In a bed of brown.

It’s cold—and I wait
For someone to shelter me
And take me from here.
Snow falling slowly
Blanketing the trees and road
Silence and beauty.

Haiku Program:

//Mad Libs Haiku

import java.util.Scanner;

public class Haiku
{
   public static void main( String[] args )
   {
   //create Scanner to get input from user
      Scanner input = new Scanner( System.in );

      String word1;//Person's name, 2 syllables
      String word2;//Noun, 2 syllables
      String word3;//Adjective, 1 syllable
      String word4;//Adjective, 1 syllables
      String word5;//Adjective, 2 syllables

      System.out.print( "Type a person's name -- two syllables: " );//prompt
      word1 = input.nextLine();//read user input

      System.out.print( "Type a two-syllable noun: " );//prompt
      word2 = input.nextLine();//read user input

      System.out.print( "Type a one-syllable adjective: " );//prompt
      word3 = input.nextLine();//read user input

      System.out.print( "Gimme another one-syllable adjective: " );//prompt
      word4 = input.nextLine();//read user input

      System.out.print( "Last one! A two-syllable adjective: " );//prompt
      word5 = input.nextLine();//read user input


      System.out.println( "\n\nHere is your Mad Libs-style haiku:\n\n" );
      System.out.printf( "I said to %s,\n", word1 );
      System.out.printf( "\"My love is like a %s:\n", word2 );
      System.out.printf( "%s, %s, and %s.\"\n", word3, word4, word5 );

   }//end method main
}//end class Haiku

No comments:

Post a Comment