Question

You will need to think about problem solving. There are several multi-step activities. Design, compile and...

You will need to think about problem solving. There are several multi-step activities.

Design, compile and run a single Java program, StringEx.java, to accomplish all of the following tasks. Add one part at a time and test before trying the next one. The program can just include a main method, or it is neater to split things into separate methods (all static void, with names like showLength, sentenceType, lastFirst1, lastFirst), and have main call all the ones you have written so far (or for testing purposes, just the one you are working on, with the other function calls commented out). Use the UI class for user input. You can copy the file into your project.

  1. Read a string from the keyboard and print the length of the string, with a label.

  2. Read a sentence (string) from a line of input, and print whether it represents a declarative sentence (i.e. ending in a period), interrogatory sentence (ending in a question mark), or an exclamation (ending in exclamation point) or is not a sentence (anything else).

    It makes sense to only make small changes at once and build up to final code. First you might just code it to check if a sentence is declarative or not. Then remember you can test further cases with else if (...).

  3. Read a whole name from a single line of user input. Do not ask for first and last names to be entered on separate lines! Assume first and last names are separated by a space (no middle name). Print last name first followed by a comma and a space, followed by the first name. For example, if the input is "Marcel Proust", the output is "Proust, Marcel".

  4. Improve the previous part, so it also allows a single name without spaces, like "Socrates", and prints the original without change. If there are two parts of the name, it should work as in the original version.

UI Class:

import java.util.Scanner;

/**
 * Aid user keyboard input with prompts and error catching.
 *  
 * @version 2017.09.24
 */
public class UI 
{
   private static Scanner in = new Scanner(System.in);

   /** Return the Scanner reading the keyboard.
    *  There should be ONLY ONE in a program.
    */
   public static Scanner getKeyboardScanner()
   {
      return in;
   }


   /** Prompt the user for a line and return the line entered.
    *  @param prompt
    *      The prompt for the user to enter the input line.
    *  @return
    *      The line entered by the user.
    */
   public static String promptLine(String prompt) {
      System.out.print(prompt);
      return in.nextLine();
   }


   /** Prompt for a character.
    *  @param prompt
    *      The prompt for the user to enter a character
    *  @return
    *     The first character of the line entered or a blank if the line
    *     is empty.
    */
   public static char promptChar(String prompt)
   {
      String line = promptLine(prompt);
      if (line.length() == 0)
         return ' ';
      return line.charAt(0);
   }

   /** Print a question and return a response.
    *  Repeat until a valid answer is given.
    * @param question
    *    The yes/no question for the user to answer.
    * @return
    *    True if the answer is yes, or False if it is no.
    */
   public static boolean agree(String question)
   {
      String yesStr = "yYtT", noStr = "nNfF", 
             legalStr = yesStr + noStr;

      char ans = promptChar(question);
      while (legalStr.indexOf(ans) == -1)
      {
         System.out.println("Respond 'y or 'n':");
         ans = promptChar(question);

      }
      return yesStr.indexOf(ans) >= 0;
   }

   /** Prompt and read an int.
    * Repeat until there is a legal value to return.
    * Read through the end of the line
    *  @param prompt
    *      The prompt for the user to enter a value.
    *  @return
    *      The value entered by the user.
    */
   public static int promptInt(String prompt)
   {
      System.out.print(prompt);
      while (! in.hasNextInt())
      {
         in.next();  // dump the bad token
         in.nextLine(); // dump through the newline
         System.out.println("!! Bad int format!!");
         System.out.print(prompt);
      }
      int val = in.nextInt();
      String rest = in.nextLine().trim(); //clear line
      if (rest.length() > 0)
          System.out.println("Skipping rest of input line.");
      return val;
   }

   /** Prompt and read a double.
    * Repeat until there is a legal value to return.
    *  @param prompt
    *      The prompt for the user to enter a value.
    *  @return
    *      The value entered by the user.
    */
   public static double promptDouble(String prompt)
   {
      System.out.print(prompt);
      while (! in.hasNextDouble())
      {
         in.next();  // dump the bad token
         in.nextLine(); // dump through the newline
         System.out.println("!! Bad double format!!");
         System.out.print(prompt);
      }
      double val = in.nextDouble();
      String rest = in.nextLine().trim(); //clear line
      if (rest.length() > 0)
          System.out.println("Skipping rest of input line.");
      return val;
   }

   /** Prompt and read a line of integers.
    * Repeat until there is a legal line to process.
    *  @param prompt
    *      The prompt for the user to enter data.
    *  @return
    *      The int values entered by the user.
    */
   public static int[] promptIntArray(String prompt)
   {
      while (true) { // exit via return statement
         String line = promptLine(prompt);
         String[] tokens = line.trim().split("\\s+");
         int n = tokens.length;
         int[] nums = new int[n];
         Scanner lineScan = new Scanner(line);
         int i = 0;
         while (i < n && lineScan.hasNextInt() )
         {
            nums[i] = lineScan.nextInt();
            i++;
         }
         if (i == n)
            return nums;
         System.out.format(
           "Bad input %s. Start your line over.\n", tokens[i]);
      }
   }

   /** Prompt and read a line of numbers.
    * Repeat until there is a legal line to process.
    *  @param prompt
    *      The prompt for the user to enter data.
    *  @return
    *      The double values entered by the user.
    */
   public static double[] promptDoubleArray(String prompt)
   {
      while (true) { // exit via return statement
         String line = promptLine(prompt);
         String[] tokens = line.trim().split("\\s+");
         int n = tokens.length;
         double[] nums = new double[n];
         Scanner lineScan = new Scanner(line);
         int i = 0;
         while (i < n && lineScan.hasNextDouble() )
         {
            nums[i] = lineScan.nextDouble();
            i++;
         }
         if (i == n)
            return nums;
         System.out.format(
           "Bad input %s. Start the line over.\n", tokens[i]);
      }
   }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

/**
*
*/
package com.HomeworkLib;

import java.util.StringTokenizer;

/**
* @author vinoth.sivakumar
*
*/
public class StringEx {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       UI ui = new UI();
      
       //Read a string from the keyboard and print the length of the string, with a label.
       String inputString = ui.promptLine("Enter a String: ");
      
       System.out.println("Length of the String \"" +inputString +"\" is " + inputString.length());
      
       //Read a sentence (string) from a line of input
      
       inputString = ui.promptLine("Enter a sentence: ");      
       if(inputString.endsWith("."))
           System.out.println("The sentence entered is declarative ");
       else if (inputString.endsWith("?"))
           System.out.println("The sentence entered is interrogatory");
       else if(inputString.endsWith("!"))
           System.out.println("The sentence entered is exclamation ");
       else
           System.out.println("ITs not a sentence");
      
       //Read a whole name from a single line of user input
      
       String name = ui.promptLine("Enter Name: ");
      
       StringTokenizer st = new StringTokenizer(name, " ");
       if(st.countTokens() == 2) {
           String fname = st.nextToken();
           String lname = st.nextToken();
          
           System.out.println(lname+", " + fname);          
       }else {
           System.out.println(name);
       }
      
      
      
      
   }

}

----------------

Output 1

Enter a String: StringToFindLength
Length of the String "StringToFindLength" is 18
Enter a sentence: This sentence is to test type of sentence.
The sentence entered is declarative
Enter Name: Vinoth Sivakumar
Sivakumar, Vinoth
------------

Enter a String: ABCDFEGHIJ
Length of the String "ABCDFEGHIJ" is 10
Enter a sentence: WHERE ARE YOU FROM?
The sentence entered is interrogatory
Enter Name: OBAMA
OBAMA

Add a comment
Know the answer?
Add Answer to:
You will need to think about problem solving. There are several multi-step activities. Design, compile 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
  • Step 4: Add code that discards any extra entries at the propmt that asks if you...

    Step 4: Add code that discards any extra entries at the propmt that asks if you want to enter another score. Notes from professor: For Step 4, add a loop that will validate the response for the prompt question:       "Enter another test score? (y/n): " This loop must only accept the single letters of ‘y’ or ‘n’ (upper case is okay). I suggest that you put this loop inside the loop that already determines if the program should collect...

  • public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc...

    public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc = new Scanner(System.in);         String choice = "y";         while (choice.equalsIgnoreCase("y")) {             // get the input from the user             System.out.println("DATA ENTRY");             double monthlyInvestment = getDoubleWithinRange(sc,                     "Enter monthly investment: ", 0, 1000);             double interestRate = getDoubleWithinRange(sc,                     "Enter yearly interest rate: ", 0, 30);             int years = getIntWithinRange(sc,                     "Enter number of years: ", 0, 100);             System.out.println();            ...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

  • In this same program I need to create a new method called “int findItem(String[] shoppingList, String...

    In this same program I need to create a new method called “int findItem(String[] shoppingList, String item)” that takes an array of strings that is a shopping list and a string for an item name and searches through the “shoppingList” array for find if the “item” exists. If it does exist print a confirmation and return the item index. If the item does not exist in the array print a failure message and return -1. import java.util.Scanner; public class ShoppingList...

  • Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args)...

    Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args) { displayWelcomeMessage(); // create the Scanner object Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { // generate the random number and invite user to guess it int number = getRandomNumber(); displayPleaseGuessMessage(); // continue until the user guesses the number int guessNumber = 0; int counter = 1; while (guessNumber != number) { // get a valid int from user guessNumber...

  • Need help debugging. first class seems fine. second class is shooting an error on s =...

    Need help debugging. first class seems fine. second class is shooting an error on s = super.getString(prompt);   third class is giving me an error in the while loop where int num = console.getInt("Enter an integer:"); //-------------------------------------------------------------------------- import java.util.Scanner; public class Console {     private Scanner sc;     boolean isValid;     int i;     double d;        public Console()     {         sc = new Scanner(System.in);     }     public String getString(String prompt)     {         System.out.print(prompt);         return sc.nextLine();...

  • I have already finished most of this assignment. I just need some help with the canMove...

    I have already finished most of this assignment. I just need some help with the canMove and main methods; pseudocode is also acceptable. Also, the programming language is java. Crickets and Grasshoppers is a simple two player game played on a strip of n spaces. Each space can be empty or have a piece. The first player plays as the cricket pieces and the other plays as grasshoppers and the turns alternate. We’ll represent crickets as C and grasshoppers as...

  • PrintArray vi Create a class called PrintArray. This is the class that contains the main method....

    PrintArray vi Create a class called PrintArray. This is the class that contains the main method. Your program must print each of the elements of the array of ints called aa on a separate line (see examples). The method getArray (included in the starter code) reads integers from input and returns them in an array of ints. Use the following starter code: //for this program Arrays.toString(array) is forbidden import java.util.Scanner; public class PrintArray { static Scanner in = new Scanner(System.in);...

  • import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads...

    import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads numbers from a file, calculates the mean and standard deviation, and writes the results to a file. */ public class StatsDemo { // TASK #1 Add the throws clause public static void main(String[] args) { double sum = 0; // The sum of the numbers int count = 0; // The number of numbers added double mean = 0; // The average of the...

  • Download PartiallyFilledArray.java. Though we studied this in class, you should still take several minutes examining the...

    Download PartiallyFilledArray.java. Though we studied this in class, you should still take several minutes examining the code so that you understand the methods of the class. /** * This is a solution to the lab, "partially filled array". * * * */ import java.util.Scanner; public class CalculateAverage { public static void main(String[] args){ PartiallyFilledArray data = new PartiallyFilledArray(); getInput(data); printResults(data); }    private static void getInput(PartiallyFilledArray data) { Scanner kbd = new Scanner(System.in); System.out.print("Enter a number (negative will end input):");...

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
ADVERTISEMENT