Question

In: Computer Science

Working with Strings The following program illustrates the use of some of the methods in the...

Working with Strings

The following program illustrates the use of some of the methods in the String class. Study the program to see what it is doing.

// ***************************************************************
// StringManips.java
// Test several methods for manipulating String objects
// *************************************************************** 
import java.util.Scanner;
public class StringManips
{
   public static void main (String[] args)
   {
      String phrase = new String ("This is a String test.");
      int phraseLength; // number of characters in the phrase String 
      int middleIndex; // index of the middle character in the String
      String firstHalf; // first half of the phrase String
      String secondHalf; // second half of the phrase String
     
      // compute the length and middle index of the phrase 
      phraseLength = phrase.length(); 
      middleIndex = phraseLength / 2;

      // get the substring for each half of the phrase 
      firstHalf = phrase.substring(0,middleIndex);
      secondHalf = phrase.substring(middleIndex, phraseLength);
      // concatenate the firstHalf at the end of the secondHalf 
      switchedPhrase = secondHalf.concat(firstHalf);

      //print information about the phrase
      System.out.println();
      System.out.println ("Original phrase: " + phrase);
      System.out.println ("Length of the phrase: " + phraseLength + " characters");
      System.out.println ("Index of the middle: " + middleIndex);
      System.out.println ("Character at the middle index: " + 
      phrase.charAt(middleIndex));
      System.out.println();
   }
}

The file StringManips.java contains this program. Save the file to your directory and compile and run it. Study the output and make sure you understand the relationship between the code and what is printed. Now modify the file as follows:

Declare a variable of type String named middle3 (put your declaration with the other declarations near the top of the program) and use an assignment statement and the substring method to assign middle3 the substring consisting of the middle three characters of phrase (the character at the middle index together with the character to the left of that and the one to the right - use variables, not the literal indices for this particular string).

Add a println statement to print out the result.

Save, compile, and run to test what you have done.

Declare two new variables city and state of type String. Add statements to the program to prompt the user to enter their hometown—the city and the state.

Read in the results using the appropriate Scanner class method - you will need to have the user enter city and state on separate lines.

Then using String class methods create and print a new string that consists of the state name (all in uppercase letters) followed by the city name (all in lowercase letters) followed again by the state name (uppercase).

So, if the user enters Lilesville for the city and North Carolina for the state, the program should create and print the string

NORTH CAROLINAlilesvilleNORTH CAROLINA

Add comment lines after each variable declaration, indicating what each variable represents.

Add comment lines for each section of the program, indicating what is done in that section.

Sample run:

Original phrase: This is a String test.
Length of the phrase: 22 characters
Index of the middle: 11
Character at the middle index: t
Middle 3 characters: Str
Enter your hometown city: Lilesville 
Enter your hometown state: North Carolina 
NORTH CAROLINA lilesville NORTH CAROLINA

Solutions

Expert Solution

import java.util.Scanner;

public class StringManips {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         String phrase = new String ("This is a String test.");
      int phraseLength; // number of characters in the phrase String
      int middleIndex; // index of the middle character in the String
      String firstHalf; // first half of the phrase String
      String secondHalf; // second half of the phrase String
      String middle3; // middle three of the phrase string
      String middle3_left,middle3_right; // left and right of middle value
      String city,state;
    
    
      //Scanner class to read the value from user
      Scanner read=new Scanner(System.in);
    
      // compute the length and middle index of the phrase
      phraseLength = phrase.length();
      middleIndex = phraseLength / 2;

      // get the substring for each half of the phrase
      firstHalf = phrase.substring(0,middleIndex);
      secondHalf = phrase.substring(middleIndex, phraseLength);
      // concatenate the firstHalf at the end of the secondHalf
      String switchedPhrase = secondHalf.concat(firstHalf);
    
      middle3_left = ""+ phrase.charAt(middleIndex-1);
      middle3_right = ""+ phrase.charAt(middleIndex+1);
      //print information about the phrase
      System.out.println();
      System.out.println ("Original phrase: " + phrase);
      System.out.println ("Length of the phrase: " + phraseLength + " characters");
      System.out.println ("Index of the middle: " + middleIndex);
      System.out.println ("Character at the middle index: " +
      phrase.charAt(middleIndex));
      System.out.println("Middle3 Characters: "+middle3_left+
              phrase.charAt(middleIndex)+middle3_right);
    
      System.out.print("Enter your hometown city: ");
      city = read.nextLine(); // reading the name of city from user
    
      System.out.print("Enter your hometown state:");
      state = read.nextLine(); // reading the name of state from user
    
      String state_allInCaps=state.toUpperCase(); // changing state all in caps letter
    
      System.out.println(state_allInCaps+" "+city+" "+state_allInCaps); // concatnating the city and state

      System.out.println();
    }
  
}

output screen:


Related Solutions

refund quesetion /**************************************************************** * FILE: dotprod_mutex.c * DESCRIPTION: * This example program illustrates the use of...
refund quesetion /**************************************************************** * FILE: dotprod_mutex.c * DESCRIPTION: * This example program illustrates the use of mutex variables * in a threads program. This version was obtained by modifying the * serial version of the program (dotprod_serial.c) which performs a * dot product. The main data is made available to all threads through * a globally accessible structure. Each thread works on a different * part of the data. The main thread waits for all the threads to complete *...
This program works with strings complete the following functionsto allow the program to function properly;...
This program works with strings complete the following functions to allow the program to function properly;a) Write a C function int string_to_number(char *) that takes a string of decimal digits as an input parameter, and returns the integer value that the string represents. For example, if the char s[] ="256", then string_to_number(s) returns integer 256 (int data type). You are allowed to use strlen(…) function, but not allowed to use atoi and other functions. Ignore the negative sign and overall.b)...
Write a simple short Java program of your choice which illustrates inheritance, polymorphism and the use...
Write a simple short Java program of your choice which illustrates inheritance, polymorphism and the use of interfaces. The program should not take up more than half a page of size A4.
For this program you will implement the following utility functions to test mastery of C strings....
For this program you will implement the following utility functions to test mastery of C strings. *******you MUST use these these function***** void removeBlanks(char *src, char *dest); void replaceChar(char *src, char oldChar, char newChar); char *flipCase(const char *src); Please read the description of these functions carefully. In the removeBlanks function you will implement a routine that takes a string in as src and outputs the same string into dest but removing any blank space character encountered. For example, if the...
In C++ please modify the following program and add characters (char) and names (strings) to be...
In C++ please modify the following program and add characters (char) and names (strings) to be added to the linked list along with integers. The current demo program accepts only integer data, so you would ask the user to select the data type to be added to the linked list. The user should be given the following three choices: (a) whole numbers (b) single characters (c) strings Once the user makes a selection from the list above then your program...
The following program should swap the vowels between two strings as long as the end of...
The following program should swap the vowels between two strings as long as the end of either string has not been reached. Example Enter the first string: james Enter the second string: naomi jamos naemi Complete the program by finishing the swap_vowels function. You may not modify ANY existing code given. #include #include #define MAX_SIZE 128 int isvowel(char c) { switch (c) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case...
3) Create a Java program that uses NO methods, but use scanner: Write a program where...
3) Create a Java program that uses NO methods, but use scanner: Write a program where you will enter the flying distance from one continent to another, you will take the plane in one country, then you will enter miles per gallon and price of gallon and in the end it will calculate how much gas was spend for that distance in miles. Steps: 1) Prompt user to enter the name of country that you are 2) Declare variable to...
PUSHING ON STRINGS The explosion of U.S. banks' excess reserves since 2008 illustrates the dramatic failure...
PUSHING ON STRINGS The explosion of U.S. banks' excess reserves since 2008 illustrates the dramatic failure of monetary policy. BY GERALD FRIEDMAN May/June 2009; updated 2018 Dollars and Sense Monetary policy is not working. Since the economic crisis began in July 2007, the Federal Reserve has dramatically cut interest rates and pumped out over $1 trillion, increasing the money supply by over 15% in less than two years. These vast sums have failed to revive the economy because the banks...
A) What is the float and how can a company use it for working capital? Provide an example that illustrates how it happens. B) If the company records indicate the following:
 A) What is the float and how can a company use it for working capital? Provide an example that illustrates how it happens.B) If the company records indicate the following:Opening amount $10,000Deposits 30,000Cheques -22,000Closing balance $18,000 The bank statement indicates that the opening amount is $10,000, the deposits are 22,000 and the cheques that have cleared are 2,000, what is the amount of the float?
Python 8.17 LAB: Strings of a Frequency Write a program that reads whitespace delimited strings (words)...
Python 8.17 LAB: Strings of a Frequency Write a program that reads whitespace delimited strings (words) and an integer (freq). Then, the program outputs the strings from words that have a frequency equal to freq in a case insensitive manner. Your specific task is to write a function wordsOfFreqency(words, freq), which will return a list of strings (in the order in which they appear in the original list) that have a frequency same as the function parameter freq. The parameter...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT