Question

This program will take the classic tongue-twister "Peter Piper picked a peck of pickled peppers." and...

This program will take the classic tongue-twister "Peter Piper picked a peck of pickled peppers." and generate a tongue twister phrase based on user input for a last name, a unit of measurement and a vegetable. For all three cases, the user input may be multiple words.

Once read, the user input will be modified to fit the following rules:

last name: No leading or trailing whitespace; the first character will be upper case and the rest lower case.

unit of measurement and vegetable: No leading or trailing whitespace; all the characters in lower case.

Consider the following example with interleaved input (Zhang\nmeter\npumpkin\n, where '\n' is a new line) and output:

Enter your last name: Zhang
Enter a unit of measurement: meter
Enter the name of a vegetable: pumpkin
A tongue twister: Peter Zhang picked a meter of pickled pumpkins.

Note that in this program, unlike the previous ones, the prompts are not followed by a newline. That is, the input is:

Zhang
meter
pumpkin

and the output is:

Enter your last name: Enter a unit of measurement: Enter the name of a vegetable: A tongue twister: Peter Zhang picked a meter of pickled pumpkins.

Suggestion: Methods in the Scanner class (next() and nextLine()), String class (trim(), substring(), toUpperCase(), charAt(), etc.) and Character class may be helpful for this program.

As the problems get more complicated, it is good to divide them up into smaller, easier to handle parts. Let's break this problem down into two parts: (1) a method for formatting the last name and (2) input and output in the main method.

(1) a) Copy the following method into your SillyString class.

    /**
     * This method returns the name with the first letter
     * in upper case and the rest lower case. Any spaces at
     * the beginning or end are removed. Does not change
     * spaces in the middle of the string.
     * For multiple word names, only the first letter of the
     * first word should be upper case, all the rest lower case.
     * @param name a name that may be mixed case.
     * @return the name in proper case.
     */
    public static String properCase(String name) {
              //FILL IN BODY
    }

b) Before implementing the properCase method, think about the different types of values that might be passed in to name. Copy the following method into your SillyString class and replace the /*FIX ME*/ with 3 different calls to the properCase method. Each call should test a different type of input to the method. You should have a minimum of 3 tests, but you may have more.

    /**
     * Runs tests on the properCase method. 
     */
    public static void testProperCase() {
       System.out.println(/*FIX ME*/);
       System.out.println(/*FIX ME*/);
       System.out.println(/*FIX ME*/);
    }

c) Implement the properCase method and use the testProperCase method to test it before submitting.

(2) Complete the main method so that the output is produced and the input is read as described above.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

If you have any problem with the code feel free to comment.

Program

import java.util.Scanner;

public class Test{
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);//for taking console input
      
       String phrase = "Peter Piper picked a peck of pickled peppers.";
       String lastName, measurement, vegetable;
       //taking user input
       System.out.print("Enter your last name: ");
       lastName = sc.nextLine();
       System.out.print("Enter a unit of measurement: ");
       measurement = sc.nextLine();
       System.out.print("Enter the name of a vegetable: ");
       vegetable = sc.nextLine();
      
       lastName = properCase(lastName);
//       testProperCase(); // for per froming the tests

       measurement = measurement.toLowerCase();
       vegetable = vegetable.toLowerCase()+".";
      
       String newPhrase = makeNewPhrase(phrase, lastName, measurement, vegetable);
       System.out.println("A tongue twister: "+newPhrase);
      
       sc.close();
   }

   private static String makeNewPhrase(String phrase, String lastName, String measurement, String vegetable) {
       String str="";
      
       String[] ar = phrase.split(" ");//spliting the phrase to array
      
       //changing the specific location
       ar[1] = lastName;
       ar[4] = measurement;
       ar[7] = vegetable;
      
       for(int i=0; i<ar.length; i++) {
           str += ar[i] + " "; //creating new phrase
       }
      
       return str;
   }
  
   //modifying the name
   public static String properCase(String name) {
      
       name = name.trim();//removing trailing spaces
       name = name.toLowerCase();//converting it to lower case
       char first = Character.toUpperCase(name.charAt(0));//converting the first letter to upper case
       name=name.replaceFirst(name.charAt(0)+"", first+"");//replacing the first letter of name
       return name;
   }
  
//   public static void testProperCase() {
//       System.out.println(properCase(" david "));
//       System.out.println(properCase("john wick"));
//       System.out.println(properCase("bURCE Wayne"));
//   }
}

Output

Add a comment
Know the answer?
Add Answer to:
This program will take the classic tongue-twister "Peter Piper picked a peck of pickled peppers." and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • read the code and comments, and fix the program by INSERTING the missing code in Java...

    read the code and comments, and fix the program by INSERTING the missing code in Java THank you please import java.util.Scanner; public class ExtractNames { // Extract (and print to standard output) the first and last names in "Last, First" (read from standard input). public static void main(String[] args) { // Set up a Scanner object for reading input from the user (keyboard). Scanner scan = new Scanner (System.in); // Read a full name from the user as "Last, First"....

  • Hello Can you help to fix the program. When running, it still show Exception in thread...

    Hello Can you help to fix the program. When running, it still show Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol symbol: class Contact location: class ContactMap    at ContactMap.main(ContactMap.java:40) C:\Users\user\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 1 second) ************************ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class ContactMap { public static void main(String args[]) throws IOException { Scanner input=new Scanner(System.in); //Create a TreeMap ,...

  • Java // Topic 2c // Program reserves airline seats. import java.util.Scanner public class Plane {    //...

    Java // Topic 2c // Program reserves airline seats. import java.util.Scanner public class Plane {    // checks customers in and assigns them a boarding pass    // To the human user, Seats 1 to 2 are for First Class passengers and Seats 3 to 5 are for Economy Class passengers    //    public void reserveSeats()    {       int counter = 0;       int section = 0;       int choice = 0;       String eatRest = ""; //to hold junk in input buffer       String inName = "";      ...

  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • Please complete the following programming with clear explanations. Thanks! Homework 1 – Programming with Java: What...

    Please complete the following programming with clear explanations. Thanks! Homework 1 – Programming with Java: What This Assignment Is About? Classes (methods and attributes) • Objects Arrays of Primitive Values Arrays of Objects Recursion for and if Statements Selection Sort    Use the following Guidelines: Give identifiers semantic meaning and make them easy to read (examples numStudents, grossPay, etc.) Use upper case for constants. • Use title case (first letter is upper case) for classes. Use lower case with uppercase...

  • This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static...

    This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static void main(String args[]) throws IOException { Scanner inFile = new Scanner(new File(args[0])); Scanner keyboard = new Scanner(System.in);    TwoDArray array = new TwoDArray(inFile); inFile.close(); int numRows = array.getNumRows(); int numCols = array.getNumCols(); int choice;    do { System.out.println(); System.out.println("\t1. Find the number of rows in the 2D array"); System.out.println("\t2. Find the number of columns in the 2D array"); System.out.println("\t3. Find the sum of elements...

  • You will be writing a simple Java program that implements an ancient form of encryption known...

    You will be writing a simple Java program that implements an ancient form of encryption known as a substitution cipher or a Caesar cipher (after Julius Caesar, who reportedly used it to send messages to his armies) or a shift cipher. In a Caesar cipher, the letters in a message are replaced by the letters of a "shifted" alphabet. So for example if we had a shift of 3 we might have the following replacements: Original alphabet: A B C...

  • package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task...

    package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task #1 before adding Task#2 where indicated. */ public class NumericTypesOriginal { public static void main (String [] args) { //TASK #2 Create a Scanner object here //identifier declarations final int NUMBER = 2 ; // number of scores int score1 = 100; // first test score int score2 = 95; // second test score final int BOILING_IN_F = 212; // boiling temperature double fToC;...

  • The following are screen grabs of the provided files Thanks so much for your help, and have a n...

    The following are screen grabs of the provided files Thanks so much for your help, and have a nice day! My Java Programming Teacher Gave me this for practice before the exam, butI can't get it to work, and I need a working version to discuss with my teacher ASAP, and I would like to sleep at some point before the exam. Please Help TEST QUESTION 5: Tamagotchi For this question, you will write a number of classes that you...

  • Summary You will write an application to build a tree structure called Trie for a dictionary...

    Summary You will write an application to build a tree structure called Trie for a dictionary of English words, and use the Trie to generate completion lists for string searches. Trie Structure A Trie is a general tree, in that each node can have any number of children. It is used to store a dictionary (list) of words that can be searched on, in a manner that allows for efficient generation of completion lists. The word list is originally stored...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT