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...

  • Language Java Step 1: Design a class called Student. The Student class should contain the following...

    Language Java Step 1: Design a class called Student. The Student class should contain the following data: firstName lastName studentID totalCredits gpa Your class should implement the “sets” and “gets” for the class. Include methods: equals, compareTo, toString. Change the toString method (from class) to put each member variable on a new line. Step 2: Write a driver program to test that Student works correctly. Test is with 3 students as given in class. Step 3: Write a “registration” program...

  • Need help debugging. Create an application that keeps track of the items that a wizard can...

    Need help debugging. Create an application that keeps track of the items that a wizard can carry. console application which has no errors: import java.util.Scanner; public class Console {        private static Scanner sc = new Scanner(System.in);     public static String getString(String prompt) {         System.out.print(prompt);         String s = sc.nextLine();         return s;     }     public static int getInt(String prompt) {         int i = 0;         boolean isValid = false;         while (!isValid) {             System.out.print(prompt);...

  • 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...

  • I need help with my Java code. A user enters a sentence and the program will...

    I need help with my Java code. A user enters a sentence and the program will tell you what words were duplicated and how many times. If the same word is in the sentence twice, but one is capitalized, it will not count it as a duplicate. How can I make the program read the same word as the same word, even if one is capitalized and the other is not? For example, "the" and "The" should be counted as...

  • 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...

  • Complete the printPalindrome method in the provided Palindrome.java program. The printPalindrome method accepts a String as...

    Complete the printPalindrome method in the provided Palindrome.java program. The printPalindrome method accepts a String as a parameter and prints whether the parameter String is a palindrome (i.e., reads the same forwards as it does backwards, for example, "abba" or "racecar"). Make the code case-insensitive, so that words like "Abba" and "Madam" will be considered palindromes. import java.util.*; /** * Determines if a user entered String is a palindrome, which means the String * is the same forward and reverse....

  • 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();...

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