Question

In: Computer Science

This programming assignment is intended to demonstrate your knowledge of the following:  Writing a while...

This programming assignment is intended to demonstrate your knowledge of the following:

 Writing a while loop  Write methods and calling methods Text Processing There are times when a program has to search for and replace certain characters in a string with other characters. This program will look for an individual character, called the key character, inside a target string. It will then perform various functions such as replacing the key character with a dollar-sign ($) wherever it occurs in the target string. For example, if the key character were 'a' and the string were "He who laughs last, laughs fast, faster, FASTEST." then the operation of replacing the 'a' by a dollar-sign would result in the new string: "He who l$ughs l$st, l$ughs f$st, f$ster, FASTEST." As you can see, only the lower-case 'a' was detected and replaced. The letter 'a' and 'A' are considered different characters. This is called "case-sensitivity" and this entire program spec is case-sensitive. This was only one possible task we might perform. Another would be to remove all instances of the key character rather than replace each with a dollar-sign. Yet a third might be to count the number of key characters. We are going to do it all. Modifying vs. Rebuilding Whenever we deal with strings, we have to decide whether we are going to modify an existing string or create a second string which has the desired changes. Since one cannot modify any string in the String class, the first option does not really exist. We will not attempt to touch the original string in our operations. Instead, we will declare a new string object and build that up in stages, replacing or removing the desired characters of the original string by simply taking action on the new string we are building. When I say we "build" a string, I mean that we initialize the string to be empty, "", and then use concatenation to replace it with ever longer versions of itself. You will use concatenation to build a string by repeatedly tagging new characters onto its end. This technique has some advantages that allow it to be used for a variety of purposes, so it's good to learn now. It might seem like we are breaking the rule that String objects cannot be modified, but we will not be changing anything. Instead, we will be replacing what the String reference points to, with a slightly longer version of the old String at every phase. For example, consider this statement, which appends an exclamation point to the end of a string, myStr: myStr = myStr + "!"; This statement uses the old value of myStr on the RHS, then completely throws away the old value on the LHS and replaces it with the new, longer, String. This is similar to a more familiar kind of numeric statement: n = n + 3; where we replace the old contents of n with new contents. _________________________________________________________________________________________________________ 2 The Methods We will be writing methods. Some will get input from the user (which take no parameters), and others will take arguments: the String and/or key character. Depending on the method we write, it will return one of the following types: a String, a char or an int. For example, one of the methods we write will take the key character and the target string as parameters and will return a new String which has all the occurrences of the key character replaced by dollar-signs. Its signature would look like this: public static String maskCharacter(String theString, char keyCharacter) In our spec, this week, we will use input methods to get the input (not main()), but we will allow main() to do the output directly. The Program Spec Ask the user to enter both a key character and a target string (phrase, sentence, etc.). Then, show the user three things: 1. The target string with the key character replaced by dollar-signs.

2. The target string with the key character removed.

3. The number of occurrences of the key character (case sensitive) in the target string. Clarification and Other Requirements

 This program does not loop for different strings. Once it processes a string, the program ends.

 Here, "character" means any printable character. They can be letters, numbers or even special symbols.  Each target input string should be complex with a mix of characters, special symbols, numbers to show how the program handles each category. All methods that are used will be static. Input Method Specs 1. char getKeyCharacter() This method requests a single character from the user and continues to ask for it until the user gets it right: this method will test to make sure the user only types one single character. 0, 2, 3 or more characters will be flagged as an error, and the method will keep at the user until he types just one character. You are not required to use a char as an input variable -- in fact, you cannot solve the problem using a char as input (you must think about this and make the appropriate choice here). What matters is that a char is returned, as a functional return, to the client, main(). 2. String getString() This method requests a string from the user and continues to ask for it until the user gets it right: this method will test to make sure the user only types a string that has at least 4 characters. Make this minimum size a constant (final), and use that symbolic constant, not the literal (4) wherever it is needed. The acquired string will be returned as a functional return. _________________________________________________________________________________________________________

3

Processing Method Specs You must write the methods below from scratch. Do not rely on any other built-in or pre-existing methods that appear to provide any of this functionality for you. There is a high value to you in practicing such logic.

3. String maskCharacter(String theString, char keyCharacter) This method will take both a string and a character as parameters and return a new string that has each occurrence of the key character replaced by a dollar-sign, '$'.

4. String removeCharacter(String theString, char keyCharacter) This method will take both a string and a character as parameters and return a new string that has each occurrence of the key character removed, but all other characters left intact.

5. int countKey(String theString, char keyCharacter) This method will take both a string and a character as parameters, and return the number of key characters that appear in the string (case sensitive). Input Errors Whenever the user makes an input error, keep at them until they get it right. Do not return from an input method until you have acquired a legal value, even if it takes years. Test Run Requirements: Submit at least three runs. In at least one of the three runs, intentionally commit input errors to demonstrate both kinds of illegal input described above. CLASS NAME.

Your program class should be called Text Processing.java.

Sample Run Please enter a SINGLE character to act as key: dgkfpo

Please enter a SINGLE character to act as key: O*(U Please enter a SINGLE character to act as key: P Please enter a phrase or sentence >= 4 and <= 500 characters: sdf Please enter a phrase or sentence >= 4 and <= 500 characters: sfd sf jko POIJ JKOLP lkjsdf psadfjP sdfj erP sdfp String with 'P' masked: sfd sf jko $OIJ JKOL$ lkjsdf psadfj$ sdfj er$ sdfp String with 'P' removed: sfd sf jko OIJ JKOL lkjsdf psadfj sdfj er sdfp # Ps: 4 CS 1A Assignment #6 Winter 2017 February 13, 2017 _________________________________________________________________________________________________________

4 Submission Instructions

 Execute the program and copy/paste the output that is produced by your program into the bottom of the source code file, making it into a comment. I will run the programs myself to see the output.  Make sure the run "matches" your source. If the run you submit could not have come from the source you submit, it will be graded as if you did not hand in a run.  Use the Assignment Submission link to submit the source code file.

 Submit the following file: o Text Processing.java

 Do not submit .class files.

Solutions

Expert Solution

import java.util.Scanner;


public class TextProcessing {

   static Scanner sc = new Scanner(System.in);
   static final int minStringLength = 4;
  
   public static void main(String[] args) {
      
       char keyCharacter = getKeyCharacter();
       String theString = getString();
      
       System.out.println();
      
//String markedString = maskCharacter(theString, keyCharacter);

String markedString = maskCharacter(theString, keyCharacter, '$');
       System.out.println("String with '"+keyCharacter+"' masked:"+markedString);
      
       String removedString = removeCharacter(theString, keyCharacter);
       System.out.println("String with '"+keyCharacter+"' removed:"+removedString);
      
       int keyCount = countKey(theString, keyCharacter);
       System.out.println("String with '"+keyCharacter+"' count:"+keyCount);
      
   }

   private static int countKey(String theString, char keyCharacter) {
      
       int keyCount = 0;
       for(int i = 0; i < theString.length(); i++) {
           char ch = theString.charAt(i);
          
           if(ch == keyCharacter){
               keyCount = keyCount + 1;
           }
   }
      
       return keyCount;
   }

   private static String removeCharacter(String theString, char keyCharacter) {
      
       String removedString = "";
       for(int i = 0; i < theString.length(); i++) {
           char ch = theString.charAt(i);
          
           if(ch == keyCharacter){
               // do nothing
           } else {
               removedString = removedString + ch;
           }
       }
      
       return removedString;
   }

   private static String maskCharacter(String theString, char keyCharacter) {

       String maskString = "";
       for(int i = 0; i < theString.length(); i++) {
           char ch = theString.charAt(i);
          
           if(ch == keyCharacter){
               maskString = maskString + keyCharacter;
           } else {
               maskString = maskString + ch;
           }
       }
      
       return maskString;
   }

private static String maskCharacter(String theString, char keyCharacter, char maskCharacter) {

       String maskString = "";
       for(int i = 0; i < theString.length(); i++) {
           char ch = theString.charAt(i);
          
           if(ch == keyCharacter){
               maskString = maskString + maskCharacter;
           } else {
               maskString = maskString + ch;
           }
       }
      
       return maskString;
   }

   private static String getString() {
      
       String string = "";
      
       while(string.length() <= minStringLength && string.length() <= 500 ) {
           string = sc.nextLine();
           System.out.print("Please enter a phrase or sentence >= 4 and <= 500 characters:");
       }
      
       return string;
   }

   private static char getKeyCharacter() {
      
       String str = "";
      
       while(str.length() != 1) {
           System.out.print("Please enter a SINGLE character to act as key:");
           str = sc.next();
       }
      
       return str.charAt(0);
   }

}

Output:


Related Solutions

This assignment is intended to test your knowledge of how to appropriately compare two means in...
This assignment is intended to test your knowledge of how to appropriately compare two means in Excel using the data file Student_Debt.xlsx. The data file has 50 randomly selected student debt amounts from 2011 and 50 randomly selected student debt amounts from 2007. You want to know whether the sample data provide enough evidence to believe there is a difference between the debt amounts in the two years. The null and alternative hypotheses are shown below. Null Hypothesis: Mean Student...
The purpose of this assignment is to enhance your writing, application of knowledge, and critical thinking...
The purpose of this assignment is to enhance your writing, application of knowledge, and critical thinking skills. In general, this assignment requires you to analyze an organization of your choice and prepare a case study covering a variety of aspects of the organization. The content will include information on the mission, strategy, culture, structure, and environment of the organization. First you need to choose an organization to examine. It can be one you worked for in the past, your present...
implement a JavaFX program to demonstrate skills and knowledge using the following: 1.General Java programming skills...
implement a JavaFX program to demonstrate skills and knowledge using the following: 1.General Java programming skills (e.g. conditionals, branching and loops) as well as object-oriented concepts) 2. Writing JavaFX applications incl. using fxml 3. • GUI Layouts (organizing UI controls) I just need some samples and explanations.
Assignment 1 – Writing a Linux Utility Program Instructions For this programming assignment you are going...
Assignment 1 – Writing a Linux Utility Program Instructions For this programming assignment you are going to implement a simple C version of the UNIX cat program called lolcat. The cat program allows you to display the contents of one or more text files. The lolcat program will only display one file. The correct usage of your program should be to execute it on the command line with a single command line argument consisting of the name you want to...
This project will require you to demonstrate proficiency in programming using TCP/IP sockets by writing both...
This project will require you to demonstrate proficiency in programming using TCP/IP sockets by writing both a client program and a server program to provide Roman numeral to Arabic number translation. The client program must accept the –s servername flag and parameter to specify the hostname of the system running the server process, as well as accept the –p port-number flag and parameter indicating the port on which the server is listening. One (and only one) of the –r or...
Demonstrate the following: Usage of Eclipse Variable Assignment Looping (for, while etc) ArrayList (using object) Object...
Demonstrate the following: Usage of Eclipse Variable Assignment Looping (for, while etc) ArrayList (using object) Object based programming User Interaction with multiple options Implementing Methods in relevant classes Instructions Start with below java files: Item.java Pages //add package statement here public class Item { private int id; private double price; public Item(int id, double price){ this.id = id; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double...
Use this assessment as an opportunity to demonstrate the breadth of your knowledge and understanding of...
Use this assessment as an opportunity to demonstrate the breadth of your knowledge and understanding of experimental design.Respond to the following question in essay format. Approximately, three to four paragraphs or 500-550 words. G. has just completed a study that shows a correlation between the amount of time children watch television and their attention spans. Assume the correlation was r = -.34. State an experimental hypothesis based on this finding and devise a simple procedure for testing it.
In this assignment will demonstrate your understanding of the following: 1. C++ classes; 2. Implementing a...
In this assignment will demonstrate your understanding of the following: 1. C++ classes; 2. Implementing a class in C++; 3. Operator overloading with chaining; 4. Preprocessor directives #ifndef, #define, and #endif; 5. this – the pointer to the current object. In this assignment you will implement the Date class and test its functionality. Consider the following class declaration for the class date: class Date { public: Date(); //default constructor; sets m=01, d=01, y =0001 Date(unsigned m, unsigned d, unsigned y);...
C Programming Game Scores Assignment Outcome: Student will demonstrate the ability to design a menu driven...
C Programming Game Scores Assignment Outcome: Student will demonstrate the ability to design a menu driven program. Student will demonstrate the ability to create and use a 2D array on the stack. Student will demonstrate the use of functions. Student will demonstrate good programming style. Program Specifications: *********************************************** ** MAIN MENU ** *********************************************** A) Enter game results B) Current Record (# of wins and # of losses and # of ties) C) Display ALL results from all games WON D)...
For your journal assignment of "multiculturalism in workplace" In your writing, reflect on the readings and...
For your journal assignment of "multiculturalism in workplace" In your writing, reflect on the readings and video this week: Your journal should show critical reflection on the course content, particularly from this week, as well as show knowledge gained and examples from the readings and video this week. I'm looking to see you engage with several of the readings and/or video(s). Remember, the more you bring up from the assigned readings, the more you are demonstrating to me that you...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT